Skip to content

Instantly share code, notes, and snippets.

@jltrem
Last active August 29, 2015 14:04
Show Gist options
  • Save jltrem/f2754fbf13de2d97f976 to your computer and use it in GitHub Desktop.
Save jltrem/f2754fbf13de2d97f976 to your computer and use it in GitHub Desktop.
static class EntityHelper
{
/// <summary>
/// Makes a shallow copy of an entity object. This works much like a MemberwiseClone()
/// but directly instantiates a new object and copies only properties that work with
/// EF and don't have the NotMappedAttribute.
///
/// ** It also avoids copying the EF's proxy reference that would occur by using MemberwiseClone() **
///
/// </summary>
/// <typeparam name="TEntity">The entity type.</typeparam>
/// <param name="source">The source entity.</param>
public static TEntity ShallowCopy<TEntity>(TEntity source) where TEntity : class, new()
{
// get the properties from the entity that are read/write and not marked with he NotMappedAttribute
var notMappedType = typeof(System.ComponentModel.DataAnnotations.Schema.NotMappedAttribute);
var sourceProperties = typeof(TEntity)
.GetProperties()
.Where(p => p.CanRead && p.CanWrite && (p.GetCustomAttributes(notMappedType, true).Length == 0));
// copy the properties into a new entity
var newObj = new TEntity();
foreach (var property in sourceProperties)
{
property.SetValue(newObj, property.GetValue(source, null), null);
}
return newObj;
}
}
@jltrem
Copy link
Author

jltrem commented Aug 2, 2014

@jltrem
Copy link
Author

jltrem commented Aug 2, 2014

this is imperfect. when using this to copy/add a record you need to be aware that reference values will be copied. Relational ref values can goof the IDs in the copy (EF will revert them to the value of the relational reference's ID)

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment