Entity framework change tracking after calling ToList()

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

Question

With regard to change tracking in EF6, I'm having trouble understanding things.

This is code that I have.

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 resembles this to some extent.

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();
    }
}

We have a list of list users, as we can see from the code in the ProcessUsers function, and we are changing that list.

However, I was always under the notion that the objects in the List (in this example, Users) were a reference back to the appropriate item in the DBSet Local collection. I now know that this works since that is how I have always done it.

After some consideration, I'm not sure that this is the case because even if the context is disposed, the list is still populated and usable (we just lose the ability to push it back to the database without additional work), so from that standpoint, the list's items must be copies of the items in the DBSet Local collection. However, if that's the case, I wouldn't have expected that changing an object in the list would affect an object in the dbset.

To sum up

What happens when I use ToList on a DBSet and how does change tracking function in this situation are the two questions at hand. - I'm aware that it functions, but I wonder whether my present perception is accurate.

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

Popular Answer

The pending modifications are recorded in a collection by EF (_context.ObjectStateManager , 8-zzz-zzz). Furthermore, when loading entities via EF, a proxy instance is returned in place of the actual entity-class. By using this proxy, EF "injects" code that updates change tracking information into your entity instances.

You lose this knowledge when you dispose of your context. Use the existing entity instance to be added to another context._context.Attach() method.

The SaveChanges() processing 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