Entity framework change tracking after calling ToList()

c# change-tracking entity-framework entity-framework-6

Question

I am struggling to understand something with change tracking in EF6.

I have code similar to this.

public class SomeClass
{
    private List<User> _users;
    private DAL _dal;

    public void ProcessUsers()
    {
        _users = _dal.GetUsers();

        foreach(var u in users)
        {
            u.user.Comment = "This is a test";
        }

        _dal.SaveChanges();
    }
}

The DAL class looks a little like this.

public class DAL
{
    ...
    private DataContext _context; // Assume that this is being newed up in a constructor.

    public List GetUsers()
    {
        return _context.Users.ToList();
    }

    public void SaveChanges()
    {
        _context.SaveChanges();
    }
}

So as we can see from the code in the ProcessUsers method we have a list of users and we are modifying that list.

Now I know that this works, Its the way I have always done it however I was always under the impression that the objects in the List (Users in this case) were a reference back to the corresponding object in the DBSet Local collection.

After a bit of thought I am not sure that this is the case as if the context is disposed the list is still populated and can be manipulated (We just loose the ability to push it back to the database without some additional work) so from that perspective the items in the list must be copies of the items from the DBSet Local collection... but if that is the case I wouldn't have though that manipulating an object in the list would have any effect on the object in the dbset as it would be a copy.

In Summary

The question is what happens when I call ToList on a DBSet and how does change tracking work in this instance? - I know it does work, but I think my current understanding might be incorrect.

1
9
6/1/2018 8:39:22 AM

Popular Answer

EF has a collection where all the pending changes are tracked (_context.ObjectStateManager, see here...). Further more loading entities with EF you get a proxy instance instead of your real entity-class. Using this proxy EF is "injecting" code into your entity instances which updates change tracking information.

When you dispose your context you loose this information. To add the existing entity instance to another context you can use the _context.Attach() method.

The SaveChanges() does process the _context.ObjectStateManager information.

1
1/11/2017 1:22:53 PM


Related Questions





Related

Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow