iloveseven
iloveseven

Reputation: 685

Why does the DbContext.Attach set an entity state to EntityState.Modified?

Why does the DbContext.Attach set an entity state to EntityState.Modified in the following example?

var db = new TestContext();
var book = new Book { 
    BookId = 1, 
    Author = new Author {
        FirstName = "Charles", 
        LastName = "Dickens" 
    } 
};
db.Attach(book); // Book Modified, Author Added - no "store generated key"

The example is taken from here.

According to the Attach method description the method:

Tells EF that the entity already exists in the database, and sets the state of the entity to Unchanged.

So, in the example above I would expect the Book to be Unchanged, but not Modified. Am I missing something here?

UPDATE

After trying out the code, I figured out that it won`t work at all. That is because we can perform the Attach operation only on a set of objects. So, the db.Attach(book); should be changed to the db.Books.Attach(book);. But still I can not understand what makes the Attach method set the state of an entity to Modified, but not the Unchanged.

Upvotes: 0

Views: 653

Answers (1)

Gabriel Luci
Gabriel Luci

Reputation: 40938

I'm not seeing the behaviour you're describing. I added this code to your fiddle:

using (var context = new EntityContext())
{
    var customer = new Customer() {CustomerID = 1};
    context.Customers.Attach(customer);
    var entity = context.Entry(customer);

    Console.WriteLine(entity.State);
}

And the output is:

Unchanged

Just like the documentation says it would be.

Maybe that comment (// Book Modified, Author Added - no "store generated key") is either a mistake, or describing that they intend to add the author to it. In that case, you would have to set the record to Modified before calling SaveChanges, or just modify whatever you want to modify after you call Attach, like this:

using (var context = new EntityContext())
{
    var customer = new Customer() {CustomerID = 1};
    context.Customers.Attach(customer);

    //change something
    customer.Description = "something";

    var entity = context.Entry(customer);
    Console.WriteLine(entity.State);
}

That would now show Modified.

Upvotes: 1

Related Questions