EF4 - Context.Entry 不可用于更改实体状态
我使用 EDMX 架构作为我的上下文。在以前的项目中,我没有使用模式,我可以像这样更改实体状态:
public void SaveProduct(Product product)
{
if (product.ProductID == 0)
context.Products.Add(product);
else
context.Entry(product).State = EntityState.Modified;
context.SaveChanges();
}
但在这个项目中,我在我的智能感知中没有看到 .Entry
(并且它不会如果我只是输入名称空间引用,则建议它)。
我尝试修改一个实体并保存它。它工作正常。
所以我的两个问题是: - 为什么 .Entry
不再出现在我的智能感知中? - 我们真的需要使用持久上下文来更改实体状态吗?或者我们可以依靠 .Net 来正确地做到这一点吗?
I use an EDMX schema as my context. On a previous project where I didn't use a schema, I could change the entity state like this:
public void SaveProduct(Product product)
{
if (product.ProductID == 0)
context.Products.Add(product);
else
context.Entry(product).State = EntityState.Modified;
context.SaveChanges();
}
But in this project, I don't see .Entry
in my intellisense (and it won't suggest a namespace reference if I just type it in).
I tried to modify an entity ans save it. It worked properly.
So my two questions are:
- Why is .Entry
not in my intellisense anymore?
- Do we really need to change the entity state with a persistent Context or can we rely on .Net to do that properly?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
我猜以前您使用过 DbContext API,但现在您使用的是 ObjectContext API - 这是使用 EF 的两种不同方法,并且每种方法都有自己的方法。检查您是否有这个(ObjectContext API):
对于您的第二个问题 - 如果您正在使用分离场景(您的实体实例不是由保存时的同一上下文实例加载的),您需要附加实体并设置状态。
I guess previously you used DbContext API but now you are using ObjectContext API - those are two different ways to use EF and each have its own way to do it. Check if you have this (ObjectContext API):
To your second question - you need to attach entity and set state if you are working with detached scenario (your entity instance is not loaded by the same context instance as it is saved).