Created
September 8, 2014 08:17
-
-
Save SamLeach/265e2822b4c5a074ecfb to your computer and use it in GitHub Desktop.
Entity Framework 4 Clone
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// 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