Linq to Entities:添加对象而不保存更改
假设我有以下代码:
TEModule teModule = Context.TEModules.Where(module => module.EnumValue.Equals(text.ModuleName)).FirstOrDefault();
if (teModule == null)
{
teModule = new TEModule();
teModule.EnumValue = text.ModuleName;
Context.TEModules.AddObject(teModule);
//Context.SaveChanges();
TEModule aux = Context.TEModules.Where(module => module.EnumValue.Equals(teModule.ModuleName)).FirstOrDefault();
}
我的问题是,如果我保留“SaveChanges”注释,那么在下一个查询中,aux 对象始终为空,因为 Context.TEModules 为空,即使当我调用“AddObject”方法。 但是,如果我在 AddObject 之后调用 SaveChanges,则在下一个查询中 aux 对象不为 null。问题是我不想如此频繁地调用 SaveChanges,因为这不是我添加对象的唯一代码段,如果我这样做,性能就会下降。
所以问题是:如果以后我需要知道该对象是否已经存在,我是否必须在每次 AddObject 调用后调用 SaveChanges?
Let's suppose I have the following code:
TEModule teModule = Context.TEModules.Where(module => module.EnumValue.Equals(text.ModuleName)).FirstOrDefault();
if (teModule == null)
{
teModule = new TEModule();
teModule.EnumValue = text.ModuleName;
Context.TEModules.AddObject(teModule);
//Context.SaveChanges();
TEModule aux = Context.TEModules.Where(module => module.EnumValue.Equals(teModule.ModuleName)).FirstOrDefault();
}
My problem is that if I keep the "SaveChanges" commented, then on the next query the aux object is always null, because Context.TEModules is empty, even when I call the "AddObject" method.
However, if I call SaveChanges after AddObject, then on the next query the aux object is not null. The problem is that I don't want to call SaveChanges so often, because this is not the only piece of code in which I add objects, and the performance goes down if I do so.
So question is: Do I have to call SaveChanges after every AddObject call, if later I need to know if the object already exists?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
linq-to-entities 查询的目的是执行,并且执行是在数据库中执行的,因此如果您没有保存实体,则其数据库表示形式不存在。
如果您需要查找本地存储的实体(尚未持久化),则必须改为查询
ObjectStateManager
。The purpose of linq-to-entities query is to be executed and the execution is performed in the database so if you didn't saved the entity its database representation doesn't exist.
If you need to find locally stored entities (not persisted yet) you must query
ObjectStateManager
instead.