sequence of updates after calling context.SaveChanges()

早过忘川 提交于 2020-01-16 09:48:10

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!