在使用state = EntityState.Modified的SaveChanges()之后,实体框架不会更新记录(Entity Framework won't update record after SaveChanges() with state=EntityState.Modified)

我正在尝试使用Entity Framework进行简单的更新。 有人能告诉我更新声明有什么问题吗?

一切顺利 - 运行时没有错误,但数据库中没有任何变化。

这是我的代码,我希望它有所帮助

var cartItem = context.Carts.FirstOrDefault(x => x.id == id); cartItem.Quantity = quantity; context.Entry(cartItem).State = EntityState.Modified; context.Carts.Attach(cartItem); context.SaveChanges();

I am trying to do a simple update with Entity Framework. Can someone tell me what's wrong with my update statement?

Everything goes smoothly - no error at runtime, however nothing gets changed in the database.

Here is my code I hope it helps

var cartItem = context.Carts.FirstOrDefault(x => x.id == id); cartItem.Quantity = quantity; context.Entry(cartItem).State = EntityState.Modified; context.Carts.Attach(cartItem); context.SaveChanges();

最满意答案

那是因为您在调用SaveChanges方法之前附加了实体:

var cartItem = context.Carts.FirstOrDefault(x => x.id == id); cartItem.Quantity = quantity; context.SaveChanges();

此外,如果您尚未禁用EF更改跟踪,则无需将状态更改为已Modified ,EF将为您完成此任务。 当您调用Attach方法时,您Attach State属性设置为Unchanged 。

你可以这样使用Attach :

var cartItem= new Cart{id=id}; //Create an instance of your entity setting the key context.Carts.Attach(cartItem);// Attach the entity to the context cartItem.Quantity = quantity; //Set the property //If you haven't disabled change tracking or proxy creation, then you don't need to change the State, EF will do it. context.Entry(cartItem).State = EntityState.Modified; context.SaveChanges();

I found the solution to my problem. The problem was not a code mistake but rather a bug in entity framework itself, when there is an aspx page with the same name as one of the objects generated by the edmx on SaveChanges instead of taking the properties of the model for the current item the or/m takes the properties of the webpage and throws null reference exception because it can't find the right values for the query. Thank you for the assist and patience by the way.

更多推荐