Tracking Entity Structure Changes After Calling ToList ()

I am trying to understand something with change tracking in FE6.

I have code similar to this one.

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 something 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 see from the code in the ProcessUsers method, we have a list of users, and we modify this list.

Now I know that this works. His way that I always did this, however, I was always impressed that the objects in the list (users in this case) were a link to the corresponding object in the local DBSet database,

After some thought, Iโ€™m not sure if itโ€™s as if the context was configured, the list is still full and can be managed (we just lose the ability to return it back to the database without any additional work), therefore, from this point of view, the elements in the list should be copies of the items from the DBSet Local collection ... but if so, I wouldnโ€™t do it, although manipulating the object in the list would affect the object in dbset, since 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 case? โ€œI know this works, but I think my current understanding may be wrong.โ€

+5
source share
2 answers

EF has a collection in which all pending changes are tracked ( _context.ObjectStateManager , see here ... ). Further loading of objects using EF, you get a proxy instance instead of your real entity class. Using this proxy EF is the "enter" code in entity instances that updates change tracking information.

When you delete your context, you lose this information. To add an existing instance of an object to another context, you can use the _context.Attach() method.

SaveChanges() processes the information _context.ObjectStateManager .

+1
source

You need to use context.TableName.Update(obejct) to mark the updated object. Then save the changes using context.Savechanges(); So in your example

 public void ProcessUsers() { _users = _dal.GetUsers(); foreach(var u in users) { u.user.Comment = "This is a test"; _dal.Users.Update(u); } _dal.SaveChanges(); } 
0
source

Source: https://habr.com/ru/post/1262635/


All Articles