Another way that works regardless of the database configuration is to make a deep clone of your object (s).
I am using Automapper ( https://www.nuget.org/packages/AutoMapper/ ) for this in my first EF project. Here is an example of code that exports a list of EF objects called "IonPair":
public bool ExportIonPairs(List<IonPair> ionPairList, string filePath) { Mapper.CreateMap<IonPair, IonPair>(); //creates the mapping var clonedList = Mapper.Map<List<IonPair>>(ionPairList); // deep-clones the list. EF 'DynamicProxies' are automatically ignored. var ionPairCollection = new IonPairCollection { IonPairs = clonedList }; var serializer = new XmlSerializer(typeof(IonPairCollection)); try { using (var writer = new StreamWriter(filePath)) { serializer.Serialize(writer, ionPairCollection); } } catch (Exception exception) { string message = string.Format( "Trying to export to the file '{0}' but there was an error. Details: {1}", filePath, exception.Message); throw new IOException(message, exception); } return true; }
source share