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

2023-09-03 13:46:15 作者:我知道坚强对于我的意义x

我用一个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).