DbContext.Entry attaching Entity

2019-06-19 01:19发布

问题:

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