Click here to Skip to main content
11,790,366 members (60,798 online)
Click here to Skip to main content

Clone an Entity in Entity Framework 4

, 11 Oct 2012 CPOL 23.7K 9
Rate this:
Please Sign up or sign in to vote.
Method to clone an EntityObject without serilization or detaching it


Entity Framework 4.0 has no in-built way to create a copy or clone an EntityObject. This simple method does just that - taking an EntityObject and returning a new one with the properties copied from the one supplied.


Two other methods have been popularized to clone an EntityObject.

  1. Serializing the object, then deseralizing it to create an exact replica deep copy, and
  2. Using the ObjectContext.Detach() method, then using the detached object as a clone.

Unfortunately, there are often problems associated when developing a front end GUI, such as a Windows Forms or WPF application with these methods, such as: the cloned copy has the same EntityKey, references to related data are lost and your UI interface loses the detached object even though the data store has not!

This third way uses reflection to copy the necessary properties to a new object of the same type.

Using the Code

Simply call the method supplying your ObjectContext, EntityObject and optionally whether you want the key Properties to be copied as well (typically when calling the method for an EntityObject, you do not want the key(s) copied, otherwise there will be a duplicate key exception when adding, however you probably will want the keys copied if you are calling the method on related data - see the example below).

public static T CopyEntity<T>(MyContext ctx, T entity, 
    bool copyKeys = false) where T : EntityObject
	T clone = ctx.CreateObject<T>();
	PropertyInfo[] pis = entity.GetType().GetProperties();
	foreach (PropertyInfo pi in pis)
		EdmScalarPropertyAttribute[] attrs = (EdmScalarPropertyAttribute[])
                      pi.GetCustomAttributes(typeof(EdmScalarPropertyAttribute), false);
		foreach (EdmScalarPropertyAttribute attr in attrs)
			if (!copyKeys && attr.EntityKeyProperty)
			pi.SetValue(clone, pi.GetValue(entity, null), null);
	return clone;

For example, say you had an entity: Customer, which had the Navigation Property: Orders. You could then copy the Customer and their Orders using the above method like so:

Customer newCustomer = CopyEntity(myObjectContext, myCustomer, false);

foreach(Order order in myCustomer.Orders)
	Order newOrder = CopyEntity(myObjectContext, order, true);

Of course newOrder will initially be related to myCustomer not newCustomer because we copied the keys from the old order. Not to worry though:newCustomer.Orders.Add(newOrder) will update newOrder to reference newCustomer.


If your EntityObject has an auto-generated key, beware not to copyKeys = true so you keep the auto-generated key.


This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)


About the Author

Zimbabwe Zimbabwe
No Biography provided

You may also be interested in...

Comments and Discussions

QuestionUsing DbContext instead of ObjectContext Pin
Member 8810587-Dec-12 2:27
memberMember 8810587-Dec-12 2:27 
I am trying to use this but using a DbContext instead of ObjectContext but I am not having any luck in changing CopyEntity to use DbContext ctx instead of ObjContext ctx.

Have you any ideas on how to change this?
GeneralMy vote of 4 Pin
Klaus Luedenscheidt11-Oct-12 17:56
memberKlaus Luedenscheidt11-Oct-12 17:56 
GeneralRe: My vote of 4 Pin
markmnl11-Oct-12 18:58
membermarkmnl11-Oct-12 18:58 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.

| Advertise | Privacy | Terms of Use | Mobile
Web04 | 2.8.1509028.1 | Last Updated 12 Oct 2012
Article Copyright 2012 by markmnl
Everything else Copyright © CodeProject, 1999-2015
Layout: fixed | fluid