ojek
ojek

Reputation: 10068

EF Code First - How does it know which objects to update?

As in the title, I have a method:

void method(MyDb db, Thread thread, Post post)
{
  thread.Title = "changed";
  db.SaveChanges();
}

(of course thread item is within MyDb object)

How does it recognize items that need to be updated? I didn't specify anywhere anything like db.Update(thread) or anything like that, it knew what to update without my help. What mechanisms are under it?

Upvotes: 1

Views: 103

Answers (1)

Ladislav Mrnka
Ladislav Mrnka

Reputation: 364279

When you load entity Thread from database it becomes by default "attached". It means EF internally keep reference to your entity and it also keeps original values of the entity when you loaded it from the database.

When you updated a title there may be two scenarios:

  • You are using change tracking proxies and EF was notified about your change so it now knows that your instance was modified and it applies those changes to database when you call SaveChanges
  • You are not using change tracking proxies and when you call SaveChanges EF goes through its internally maintained list of entity references and check if any entity has any property different from original values - all such entities and their modified properties are updated to database during SaveChanges

You can read more about that process here.

Upvotes: 3

Related Questions