EF4 - Context.Entry不可更改实体状态 [英] EF4 - Context.Entry isn't available to change an Entity State

查看:261
本文介绍了EF4 - Context.Entry不可更改实体状态的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我用一个EDMX架构作为我的背景。在一个previous项目中,我没有用一个模式,我可以改变这样的实体状态:

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();
}

但在这个项目中,我没有看到 .Entry 在我的智能感知(它不会建议一个命名空间的引用,如果我只需键入它)。

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

我试图修改一个实体ANS保存。它工作正常。

I tried to modify an entity ans save it. It worked properly.

所以,我的两个问题是: - 为什么 .Entry 不在我的智能感知了吗? - 难道我们真的需要改变了持续的背景下的实体状态,或者我们可以依靠净做正确

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?

推荐答案

我猜previously您使用的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):

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

这篇关于EF4 - Context.Entry不可更改实体状态的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆