DbContext.Entry attaching Entity

为君一笑 提交于 2019-12-08 22:10:20

问题


From my research, I read that calling DbContext.Entry(someEntity) would automatically attached the entity to the context.

However, when I do this I find that the entity's state is detached.

Can anyone shed some light on this and how the DbContect.Entry works. I'm using EF 5.0

Thanks.


回答1:


If you're wanting to attach an object, what you actually want is DbSet.Attach. DbContext.Entry is only giving you information about the entity, and allows you to change the state if it's already been attached.

Here's a good post about entity states from MSDN




回答2:


Since the answer from @Mark Oreta isn't complete:

Following the link he posted and reading the whole post revealed some different information: So DbContext.Entry(someEntity) actually is attaching the entity to the context if you set the correlating EntityState you need.

To attach a modified or added entity you could do:

using(var yourDbContext = new YourDbContext())
{
    yourDbContext.Entry(yourEntity).State =
        yourEntity.ID == 0 ?
            System.Data.Entity.EntityState.Added :
            System.Data.Entity.EntityState.Modified;
}

To attach an unmodified entity you could do:

using(var yourDbContext = new YourDbContext())
{
    yourDbContext.Entry(yourEntity).State = System.Data.Entity.EntityState.Unchanged;
}


来源:https://stackoverflow.com/questions/12831961/dbcontext-entry-attaching-entity

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