实体框架保留幽灵实体?
让我们把这个简单化... 假设我有 2 个实体:
Application Id: int (primary key, autoincrement) Name: string(60) Client: User SupportEngineer: User User Id: int (primary key, autoincrement) Name: string(60) EmailAddress: string(60)
假设我还有一个名为 Create 的方法,该方法正在接收创建的应用程序实例(在另一层中),而不涉及上下文:
var application = new Application { Name = "Visual Studio 2010", Client = new User { Id = 12 }, SupportEngineer = new User { Id = 14 } };
请注意,数据库中存在 Id == 12 和 == 14 的用户! !
public void Create(Application application) { application.Client = Context.Users.FirstOrDefault(e => e.Id == application.Client.Id); application.SupportEngineer = Context.Users.FirstOrDefault(e => e.Id == application.SupportEngineer.Id); Context.Applications.AddObject(application); Context.SaveChanges(); }
当我在调用 SaveChanges 之前检查 Context 中的对象时,我得到了在调用 Create 方法之前创建的 User 对象作为“添加”。
如果我使用数据库中的对象覆盖属性 Client 和 SupportEngineer 的值,为什么会发生这种情况? 为什么手动创建的对象(new User { Id = 12 }、new User { Id = 14 }
)仍然存在,而且处于“已添加”状态的上下文中?
Let's make this simple...
Suppose I have 2 entities:
Application Id: int (primary key, autoincrement) Name: string(60) Client: User SupportEngineer: User User Id: int (primary key, autoincrement) Name: string(60) EmailAddress: string(60)
Suppose also I have a method named Create that is receiving an instance of Application created (in another layer) without the Context beign involved:
var application = new Application { Name = "Visual Studio 2010", Client = new User { Id = 12 }, SupportEngineer = new User { Id = 14 } };
Note that User with Id == 12 and == 14 exists in the database!!
public void Create(Application application) { application.Client = Context.Users.FirstOrDefault(e => e.Id == application.Client.Id); application.SupportEngineer = Context.Users.FirstOrDefault(e => e.Id == application.SupportEngineer.Id); Context.Applications.AddObject(application); Context.SaveChanges(); }
When I inspect the objects in the Context before the call to SaveChanges, I get the User objects created before calling the Create method as "added".
Why that is happening if I'm overriding the values of the properties Client and SupportEngineer with objects from the database?
Why the mannually created objects (new User { Id = 12 }, new User { Id = 14 }
) are still around, moreover in the context with "added" state?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
只需这样做:
并让 Create 方法创建对象:
不是直接答案,而是一些一般建议:
您可能需要注意的另一件事是,它看起来好像您正在重用 DbContext。这通常是一个坏主意,特别是在添加/删除对象时。例如,在删除之后,上下文仍然知道已删除的对象。相反,我会推荐这样的模式:
Just do this:
And have the Create method just create the object:
Not a direct answer but some general advise:
Another thing you might want to watch out for, it looks as if you're reusing your DbContext. This is generally a bad idea, especially when adding/deleting objects. For example after a delete, the deleted objects are still known by the context. Instead I'd recommend a pattern like: