EF4 - Context.Entry isn't available to change an Entity State

让人想犯罪 __ 提交于 2019-12-06 07:21:27

问题


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?


回答1:


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



来源:https://stackoverflow.com/questions/9398977/ef4-context-entry-isnt-available-to-change-an-entity-state

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!