Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Entity Framework not saving changes

Tags:

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?

like image 878
Icemanind Avatar asked Mar 04 '12 21:03

Icemanind


People also ask

How do I save changes in Entity Framework?

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.

Which of the following method of the DbContext is used to Save the entities to the database?

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 .


2 Answers

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(); 
like image 172
veblock Avatar answered Nov 04 '22 12:11

veblock


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;               }   ...  } 
like image 21
Stefano Altieri Avatar answered Nov 04 '22 11:11

Stefano Altieri