When I insert a new Item in a DBSet like:
var newItemAdded = MyDBSet.Add(itemToAdd);
Then I save the changes in the DB like:
MyContext.SaveChanges();
My variable newItemAdded has been updated with the new Id auto generated by the DB.
I went to EF Core Github to see the logic, but with the big amount of files in the repository, I'm not sure to understand the logic behind.
My concern is more about how the SaveChanges executed after the insert could update newItemAdded. EF does not seem to use ref.
Maybe someone already know how does it work?
Thanks
This works, without
ref:We never needed
refto make sure that the Id of the person set inside SaveChanges survived and was seen bypafter SaveChanges was done.Conceptually this is what happens in memory when the SaveChanges code above is called:
refis a mechanism that would allow SaveChanges to swap the passed in Person out for a wholenewPerson. If you had a SaveChanges like:Then the objects in memory steps would look like:
Suppose we use ref:
refmeanspandperare the same reference. There isn't an additional one made, which could be pointed somewhere else whilepstayed pointing at JohnImagine that
reftemporarily renamedptoperand thus the SaveChanges method doingper = new Personalso affectsp. It could be thought of as like:When EF core saves the changes, it doesn't wholesale replace the entity you passed in with a new entity; it modifies some of the data inside the entity. It doesn't need
reffor your code to see the changes it madeIt doesn't even matter that EF is a two step process - you pass your entity into Add, EF stores it in an internal list, when it SaveChanges() it accesses the data via its own reference for it, but because there is only one data and both your variable and EF's list point to the same data, when EF changes the data your variable sees it, because it's the same data at the same memory location