Search code examples
sql-serverasp.net-mvcentity-frameworkc#-4.0auto-increment

Updating a ModelState's data with an auto-increment ID


I have a method that performs an insert into a table using Entity Framework 6. The table has an ID field that is populated automatically when it is written to SQL Server. I would like the method to return all of the data that was previously in the ModelState as well as the new record. When I run this code, I get everything except for the new record's ID, which comes back as a 0.

How can I rework this so it returns the new ID as well as the rest of the data from ModelState?

   [AcceptVerbs(HttpVerbs.Post)]
    public ActionResult EditingInline_Create([DataSourceRequest] DataSourceRequest request, Book book)
    {
        if (bookViewModel != null && ModelState.IsValid)
        {
            MyRepository db = new MyRepository();
            db.Books.Add(book);
            db.SaveChanges();
        }

        return Json(ModelState.ToDataSourceResult());
    }

Solution

  • Function Add return from db result of adding with correct id parameter.

    Try this:

    book = db.Book.Add(book);
    

    It give you what you want.

    If you want return model and modelstate use this:

    return Json(new[] { book }.ToDataSourceResult(request, ModelState);