Skip to content

Instantly share code, notes, and snippets.

@SamLeach
Created September 8, 2014 08:17
Show Gist options
  • Save SamLeach/265e2822b4c5a074ecfb to your computer and use it in GitHub Desktop.
Save SamLeach/265e2822b4c5a074ecfb to your computer and use it in GitHub Desktop.
Entity Framework 4 Clone
// http://www.codeproject.com/Tips/474296/Clone-an-Entity-in-Entity-Framework
// Static
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;
}
// On Generic Repository
public TEntity CopyEntity(TEntity entity, bool copyKeys = false)
{
var clone = this._context.CreateObject<TEntity>();
var pis = entity.GetType().GetProperties();
foreach (var pi in pis)
{
var 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;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment