Click here to Skip to main content
15,885,757 members
Articles / Programming Languages / C#
Tip/Trick

Clone an Entity in Entity Framework 4

Rate me:
Please Sign up or sign in to vote.
4.83/5 (5 votes)
11 Oct 2012CPOL2 min read 43.5K   10   3
Method to clone an EntityObject without serilization or detaching it

Introduction

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.

Background

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).

C#
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)
				continue;
				
			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:

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

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

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.

Caveats

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

License

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


Written By
Zimbabwe Zimbabwe
This member has not yet provided a Biography. Assume it's interesting and varied, and probably something to do with programming.

Comments and Discussions

 
QuestionUsing DbContext instead of ObjectContext Pin
Member 8810587-Dec-12 2:27
Member 8810587-Dec-12 2:27 
GeneralMy vote of 4 Pin
Klaus Luedenscheidt11-Oct-12 17:56
Klaus Luedenscheidt11-Oct-12 17:56 
GeneralRe: My vote of 4 Pin
markmnl11-Oct-12 18:58
markmnl11-Oct-12 18:58 

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

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