LINQ - how to make change tracking work when entity passed to another class as property
Here's the scenario:
I have an ASP.NET user control that runs a LINQ query, stores the results in a generic List, then dynamically loads another user control (into a Placeholder) and passes one of the objects from the List to the control through a property on the control.
The child control displays data from the object and allows the user to alter various fields. A Save button on the parent control calls a "SaveInput" method on the child control which updates the object's properties from the inputted data (no DataContext has been created at this point).
The problem is that I can't seem to use the DataContext's SubmitChanges method to save the updated object. Here is what I have tried:
If I call SubmitChanges from th开发者_运维问答e parent control, it doesn't recognise that there are changes to save, even though when you examine the original object (in the parent control's List) it has clearly got new property values. I guess this is because the changes were not made through the parent control's DataContext.
If I try (in the parent control's code) to Attach the object to the DataContext I get an error that it is already attached (well it is, so fair enough).
If I create a DataContext (in the child control's code) then try to Attach the object to it, I get an error that it is already attached to another DataContext (again, this is true)
So my clunky solution is to create a DataContext (in the child control's code) then create a new instance of the object's type, then set each property on this new object from the equivalent on the altered object, then SubmitChanges. Not elegant, but it works.
Is there a better way?
I would recommend re-pulling the exact record from your new DataContext something like
ctxt.Table.Where(x => x.ID == recordYouHave.ID).FirstOrDefault()
And then save the changes to that record before calling 'SubmitChanges'.
The other solution is to preserve the context you used to fetch the original record, but You do not want to do that! Every context should be short lived. This will explain it better than I can.
EDIT: Something worth noting that I should have mentioned, though, is that you can attach an entity to a new context, but you have to pull the original record again so it really doesn't save another database call. You just don't have to assign the properties of the object:
var orig = ctxt.Table.Where(x => x.ID == recordYouHave.ID).FirstOrDefault();
ctxt.Table.Attatch(orig, recordYouHave);
精彩评论