I have some .NET 4 entity framework objects that I get from the DB, then I serialize them to XML. Then I quit the WPF app (clear out the memory). Then I restart the WPF app and I read them (deserialize) back into a List<> but never attach them to any EF context. When I call SaveChanges() on my object context, it cretes duplicate records, but I never attached the deserialized to the context so I'm not sure why the new context is creating copies of the records. Does this have something to do with self-tracking entities http://msdn.microsoft.com/en-us/library/ff407090.aspx?
Here's a review...
Start app
Query objects into an ObjectSet.ToList() _cachedRates
IQueryable<Rate> query = DB.EF.Rates.Where({some predicates});
if (query != null && query.Count() > 0)
_cachedRates = query.ToList();
Serialize to XML
XmlSerializer serializer = new XmlSerializer(_cachedRates.GetType());
TextWriter textWriter = new StreamWriter(saveDialog.FileName);
serializer.Serialize(textWriter, _cachedRates);
textWriter.Close();
Close the app
...{later}...
Start the app again
Load the objects from an XML file, the objects are never Attach()-ed or AddObject()-ed to any context.
if (openDialog.ShowDialog().Value)
{
_cachedRates = null;
XmlSerializer deserializer = new XmlSerializer(typeof(List<Rate>));
TextReader textReader = new StreamReader(openDialog.FileName);
_cachedRates = (List<Rate>)deserializer.Deserialize(textReader);
textReader.Close();
}
If the user presses the "Save" button it ca开发者_运维知识库lls .SaveChanges() on a context
PROBLEM: I now have twice as many matching rows in my table
Since you are serializing your objects away from one context and then deserializing them back into object with a different context, you will see this behavior. Once you detach an object/item from the current context, if you open another context and do not reattach it to the current context, the context will think that it is a new object. One option in this scenario might be to us the ids of the rates that you have cached to pull those rates from the context prior to the .SaveChanges() method being called on the context and then working with those rates from the context instead of the cached object. I end up needing to do something very similar to this in my current MVC application as I am sending in a complex model via JSON and if I want the child collections to save properly, I need to copy and attach the parent object to the context with empty child collections. Then I query the child objects in each property on the JSON object directly from the context and assign the ones from the context to the child objects of the attached object before saving. This seems to work for me. If I try to just save the deserialized JSON object with the children, I end up getting duplicate child rows in my database.
精彩评论