I’ve recently come across a problem that I thought it would be simple to solve by using Entity Framework. I wanted to duplicate an object to make things easier for me and, ultimately, to the user, but I guess my assumption was incorrect. After some tests with reflection, google searches and a lot or brainstorming I’ve reached the conclusion that in Entity Framework there isn’t a built-in or clear method that allows developers to clone objects and then persist the newly created object with some changes.
You’ve probably tried to clear EntityKeysValue members and got the readonly exception right? – EntityKey values cannot be changed, once their value is set. Well, in this article I’ll show a way that I’ve found to be the simplest (thanks Patrick!).
It’s basically a serialization solution, and by that we all know it isn’t very performance-wise option, but it seems that, for now, it’s the simplest, and all we’ve got:
private static T DataContractSerialization(T obj)
DataContractSerializer dcSer = new DataContractSerializer(obj.GetType());
MemoryStream memoryStream = new MemoryStream();
memoryStream.Position = 0;
T newObject = (T)dcSer.ReadObject(memoryStream);
You can use this method by using the System.Runtime.Serialization namespace.