SaveChanges 不保存更改
我有一个使用 EF 按预期加载所有数据的应用程序,但是,在保存时,我根本无法让它工作。
我从简单开始,仅使用组合框中的值来更改数据库中的 1 个字段。当值更改时,它
this.t.Incident.AssignedTeamID = (int)this.cbTeam.SelectedValue;
会执行我还确认这将 EntityState
更改为 Modified
并且该值是我期望的值。尽管如此,调用
hdb.SaveChanges();
不会将任何内容保存回数据库。我知道这可能是我错过的一些简单的东西,但我根本不知道那是什么。
更新: 在使用 SaveChanges 之前添加 hdb.context.Attach(this.t.Incident);
会导致 InvalidOperationException
指出“实体对象不能被多个实例引用IEntityChangeTracker。”
如果有什么区别的话,这是一个桌面应用程序,而不是一个 Web 应用程序
I have an application that loads all the data as expected using EF, however, when it comes to saving, I can't get it to work at all.
I've started off simple, by just using a value from a combobox to alter 1 field in the database. When the value is changed, it executes
this.t.Incident.AssignedTeamID = (int)this.cbTeam.SelectedValue;
I've also confirmed that this changed the EntityState
to Modified
and that the value is what I expect it to be. Despite this, calling
hdb.SaveChanges();
doesn't save anything back to the database. I know it's probably something simple I'm missing, but I cannot find out what that is at all.
Update:
Adding hdb.context.Attach(this.t.Incident);
before using SaveChanges results in an InvalidOperationException
stating "An entity object cannot be referenced by multiple instances of IEntityChangeTracker."
If it makes any difference, this is a desktop application, not a web application
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
最有可能的是,由于您正在使用网络应用程序,因此您会遇到断开连接的对象上下文的问题。对于所有 ORM,您必须通过附加过程来更新实体。 SaveChanges 永远不会在请求/响应双方都起作用。
Most likely, since you're working with a web app, you have a problem with a disconnected obect context. With all ORMs, you must go through an attach process to update an entity. SaveChanges will never work on both sides of the request/response.
感谢所有在这里发帖的人。阅读这些详细信息后,答案非常简单。
正如达米安(Damien)对最初问题的评论那样,我需要做的是确保它全部从同一个类加载。
目前,我在需要时创建了数据库的私有实例,没有真正考虑。这很好,它按照我的预期加载了数据,但这意味着我将通过不同的类加载大约 3 个不同的数据库实例。
本质上,我试图使用不同的数据库实例来保存来自不同类的对象。将 save 方法移回到创建它的类(大概应该一直如此)解决了这个问题。
Thank you to everybody who posted here. The answer was quite simple after reading these details.
What I needed to do, as Damien commented on the original question, was to ensure it was all loaded from the same class.
I currently created a private instance of the DB whenever needed, without really thinking. This was fine, it loaded the data as I expected, but meant that I would have around 3 different instances of the database loaded via different classes.
Essentially, I was trying to save the object from a different class with a different instance of the database. Moving the save method back to the class it was created from (presumably like it should have always been) resolved the issue.