Reputation: 799
I'm investigating a bug in our systems and when reviewing the code I saw that the developer queried twice the same entity and saved it with different values.
I simplified the case for example:
Person Data:
id | name | age | HasLicence
1 | david | 27 | true
using (DbContext dbContext = new DbContext())
{
Person person1 = dbContext.Persons.FirstOrDefault(p=>p.age == 27);
Person person2 = dbContext.Persons.FirstOrDefault(p=>p.name == "david");
person1.HasLicence = false;
person2.HasLicence = true;
.
.
// more logic..
.
.
dbContext.SaveChanges();
}
Does this will save the entity to the database synchronously? throw exception?
Upvotes: 0
Views: 39
Reputation: 780
Simple answer is both variables are referencing same object instance(proxy).
So when you update person1.HasLicence same value will be on person2.HasLicence.
a.HasLicence = true;
Assert.AreEqual(a.HasLicence , b.HasLicence );
b.HasLicence = false;
Assert.AreEqual(a.HasLicence , b.HasLicence );
_dataContext.Save(); // updates only one entity
Behavior might be different if you have some changed settings for datacontext.
IF you want to know more how entity frameworks works you can access it on github
Upvotes: 1