I've got an MVC web application that uses SQL Server 2008 as a back end database along with the Entity Framework. The application is working fine and pulling data from the database just fine. My problem is, when it does an update to the data, it doesn't appear to be saving it. I am using the follow function:
public void SaveProduct(Product product) { if (product.ProductID == 0) { context.Products.Add(product); } context.SaveChanges(); // Breakpoint here }
This function is defined in my repository code. I set a breakpoint on the line commented above and the application is breaking at the line, so I know its hitting that line and the changes are all good in the context object. No error occurs, EF simply isn't saving the changes for some reason.
I believe my connection string is correct, since its pulling the data just fine, but here it is just in case:
<connectionStrings> <add name="EFDbContext" connectionString="Data Source=localhost;Initial Catalog=WarehouseStore;Integrated Security=True;Pooling=False" providerName="System.Data.SqlClient"/> </connectionStrings>
Anyone have any ideas on what could cause this?
Entity Framework Core Save Changes to the database using the SaveChanges method of DbContext. When we use the SaveChanges it prepares the corresponding insert , update , delete queries. It then wraps them in a Transaction and sends them to the database. If any of the queries fails all the statements are rolled back.
The SaveChanges method of the DbContext prepares the Insert , Update & Delete Queries. It does so by tracking the changes to each of the entities' context is tracking. Whenever we query the database for entities, the context retrieves them and mark the entity as Unchanged .
If you are after the insert/update functionality you have to cover both cases:
if (product.ProductID == 0) { context.Entry(product).State = EntityState.Added; } else { context.Entry(product).State = EntityState.Modified; } context.SaveChanges();
Thanks to @veblok I found the solution to my issue. There is an option in the DbContext class to prevent EF to track object by default. Once removed it EF started behaving as expected.
public class My Context : DbContext { public MyContext() { // REMOVE this or use veblok's solution this.Configuration.AutoDetectChangesEnabled = false; } ... }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With