Saeldin
Saeldin

Reputation: 397

How does Entity Framework Core handle instances before context is saved?

How does Entity Framework work when something like the following occurs:

var myInstance = new MyObject();

// Do stuff

_myContext.MyObjects.Add(myInstance);

myInstance = null;

_myContext.SaveChanges();

I ran into this happening in a complex foreach-call and it still seem to do what was expected. But I am curious how it handles it and if it gives up tracking the object when the instance is null.

Upvotes: 1

Views: 25

Answers (1)

Ivan Stoev
Ivan Stoev

Reputation: 205619

I am curious how it handles it and if it gives up tracking the object when the instance is null

In your example, the instance is not null - just the variable myInstance value is null, i.e. the variable does not hold reference to the object you've created.

What about how EF Core tracks the instances, in simplified form you can think of that as MyObjects being a List<MyObject> (the actual implementation of course is different). So what happens when you do something like this:

var myObjects = new List<MyObject>();

var myInstance = new MyObject();

// Do stuff

myObjects.Add(myInstance);

myInstance = null;

myInstance variable is null, but myObjectList holds a reference to the created object (i.e. is "tracking" it), so it can always be get back, in this case with

var trackedInstance = myObjects[0];

Again, the actual implementation is different, but the concept is the same - the DbContext instance contains some sort of a list with all "tracked" entity instances and their state (Added, Deleted, etc.).

Upvotes: 2

Related Questions