Problem:
When I change an XElement field in a Linq to SQL class and call SubmitChanges on the data context, it doesn't update. Linq to SQL seems to just flat out ignore XElement's change notifications.
Solution:
LINQ to SQL only understands changes by comparing the current and original values of data fields. When you first modify an entity, L2S makes a backup copy of the entity by copying all the field values into a new object instance. It does not do a deep copy, so values like XElements are copied over by reference. L2S treats all valus in fields as immutable, therefore the value is only ever considered changed for a reference type if the reference has actually changed. In your example, the XElement itself never changes but its contents do. L2S will not see the difference, since both current and original values of the field refer to the same XElement instance.
The same problem exists if you model binary data using a byte array. Since an array is mutable, if you change the contents of the array without changing the array itself, L2S will not see it.
The solution is to create an entirely new XElement object (based on the original) and assign it to the field in the entity.
Let's se an example:
// retrieve XElement from database
InterviewTbl dbInterviewData = _context.InterviewTbls.SingleOrDefault(c => c.UserAccountId == 2);
// create new XElement passing to constructor the XElement retrieved from database
XElement element = new XElement(dbInterviewData);
//modify the new XElement
element.Element("nameOfNode").Remove();
//Assing the new XElement to the database XElement
dbInterviewData.InterviewData = element;
//submit changes
_context.SubmitChanges();
Wednesday, September 2, 2009
Subscribe to:
Post Comments (Atom)
Thanks man! You saved my brains from blowing up!
ReplyDeleteI concur with what Yuriy said. I spent all day trying to figure out what the heck is going on. It's about to drive me nuts.
ReplyDeleteThanks so much for this blog, Reuf.
Han