6

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.

4

2 回答 2

7

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

于 2012-10-11T03:57:47.737 回答
0

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;
}
于 2017-06-26T12:17:11.837 回答