Updating the Record with EntityState.Modified but its inserting the new row rather than update

c# entity-framework-6

Question

I am using EF6 and in this i am trying to update the existing record in the database by using the EntityState.Modified state but its inserting the new row in the table rather tha updating it.I am using following code please let me know where i am going wrong.

public Product UpdateProduct(ProductVM objProduct)
{
    Product obj = new Product();
    obj = JsonConvert.DeserializeObject<Product>(JsonConvert.SerializeObject(objProduct));
    DbContext.Entry(obj).State = EntityState.Modified;
    DbContext.SaveChanges();
    return obj;
}
1
0
1/31/2016 11:15:09 AM

Accepted Answer

This is happening because Entity Framework is "unaware" of this entity of yours. You are passing just a view model and even though you know it has a PK or FK, there's no way EF knows what to do, so it creates a new one. See that you create a new Product()? This line, creates a new Product and since it is new, EF will treat its state as Added.

Instead, you need to first get your object from DB then change the fields. Something like this:

public Product UpdateProduct(ProductVM objProduct)
{
    obj = JsonConvert.DeserializeObject<Product>(JsonConvert.SerializeObject(objProduct));

    //Get the product from DB to update
    var product = DbContext.SingleOrDefult(x => x.Id == objProduct.Id);

    //update fields...
    product.SomeField = obj.SomeField;

    //Save changes
    DbContext.Entry(product).State = EntityState.Modified;
    DbContext.SaveChanges();

    return product;
}

If this Product has foreign keys to other tables you should check this question and answer too:

Difference between updating an entity by using a foreign key and using the navigation properties In Entity Framework

2
1/31/2016 11:46:45 AM


Related Questions





Related

Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow