问题
Below is an example from my textbook,
public class ContactDetails
{
public long Id { get; set; }
public string Name { get; set; }
public long SupplierId { get; set; }
public Supplier Supplier { get; set; }
}
public class Supplier
{
public long Id { get; set; }
public string Name { get; set; }
public ContactDetails Contact { get; set; }
}
so the author try to swap supplier between two ContactDetails objects details(let's say its alias is A) and targetDetails (let's say its alias is B) as:
//Part A
ContactDetails targetDetails = context.Set<ContactDetails>().FirstOrDefault(cd => cd.SupplierId == targetSupplierId);
targetDetails.SupplierId = details.Supplier.Id;
Supplier temp = new Supplier { Name = "temp" };
details.Supplier = temp;
context.SaveChanges();
//Part Two
temp.Contact = null;
details.SupplierId = targetSupplierId.Value;
context.Suppliers.Remove(temp);
context.SaveChanges();
I can uderstand Part B, but for Part A, I'm a little bit confused, I get the idea that it try to set A's SupplierId to B's first then set a newly created Supply object to A so that B can use A's supplier, but I can think of one problem:
How can EF guarantee that A's supplier is set to the new supplier temp first after calling context.SaveChanges();?
Let's say after calling context.SaveChanges();, EF assign A's supplierId to B's supplierId first, so B has A's supplier id, but in the database level, A is still having its original supplier id, but B now also has the same suppler id, which is against the one to one relationship?
来源:https://stackoverflow.com/questions/57503120/sequence-of-updates-after-calling-context-savechanges