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;
}
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