Answered by:
How to clone/duplicate an entity?

Question
-
Monday, July 7, 2008 9:21 PM
Answers
-
This is the best way I know of at this time:
Code Snippetprivate static T DataContractSerialization<T>(T obj) {
DataContractSerializer dcSer = new DataContractSerializer(obj.GetType());
MemoryStream memoryStream = new MemoryStream();dcSer.WriteObject(memoryStream, obj);
memoryStream.Position = 0;T newObject = (T)dcSer.ReadObject(memoryStream);
return newObject;
}Tuesday, July 8, 2008 1:01 AM
All replies
-
This is the best way I know of at this time:
Code Snippetprivate static T DataContractSerialization<T>(T obj) {
DataContractSerializer dcSer = new DataContractSerializer(obj.GetType());
MemoryStream memoryStream = new MemoryStream();dcSer.WriteObject(memoryStream, obj);
memoryStream.Position = 0;T newObject = (T)dcSer.ReadObject(memoryStream);
return newObject;
}Tuesday, July 8, 2008 1:01 AM -
There are more efficient ways to do it (that i.e. do not end up creating 3 copies in memory), but arguably they are much more complicated.
Tuesday, July 8, 2008 3:04 PM -
Matthieu Mezil has written something for cloning entities
http://msmvps.com/blogs/matthieu/archive/2008/05/31/entity-cloner.aspx
It's a lot of code and he's using Reflection not MetadataWorkspace . I'm sure there's a reason for that. Either way, the code is available on his blog and it's something you can use generically.
If you look a little later in his blog, you'll see he modified it to accommodate graphs.
Tuesday, July 8, 2008 3:16 PM -
Hi
In fact, I use reflection because my first idea was to do a cloner for everything (not only for entities).
What is cool on my Cloner is the fact that I use reflection only once per entity type.
"To clone an entity, I use reflection but the problem of Reflection is it’s far. The way to Clone a product is always the same. So I generate a Delegate on the fly during first call and I always use it."
Wednesday, July 9, 2008 6:17 PM -
Hi Patrick,
The code snippet which u proposed was not useful when I am trying to clone an Lazy Loaded object.
Can you provide me the solution for this problem???
Tuesday, November 27, 2012 4:39 AM -
This is a great series of articles: http://msdn.microsoft.com/en-US/data/jj592677
using (var context = new BloggingContext())
{
var blog = context.Blogs.Find(1);
var clonedBlog = (Blog)context.Entry(blog).GetDatabaseValues().ToObject();
}Note the original line was as follows but you need the cast (as is shown above):
var clonedBlog = context.Entry(blog).GetDatabaseValues().ToObject();
Jan Narkiewicz
Wednesday, July 10, 2013 6:46 PM