EF4 - Context.Entry 不可用于更改实体状态

发布于 2025-01-08 06:15:41 字数 509 浏览 2 评论 0原文

我使用 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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

﹏雨一样淡蓝的深情 2025-01-15 06:15:41

我猜以前您使用过 DbContext API,但现在您使用的是 ObjectContext API - 这是使用 EF 的两种不同方法,并且每种方法都有自己的方法。检查您是否有这个(ObjectContext API):

context.ObjectStateManager.ChangeObjectState(product, EntityState.Modified);

对于您的第二个问题 - 如果您正在使用分离场景(您的实体实例不是由保存时的同一上下文实例加载的),您需要附加实体并设置状态。

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):

context.ObjectStateManager.ChangeObjectState(product, EntityState.Modified);

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).

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文