Last active
August 29, 2015 14:04
-
-
Save jltrem/f2754fbf13de2d97f976 to your computer and use it in GitHub Desktop.
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
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; | |
} | |
} |
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
original code taken from http://stackoverflow.com/questions/12315233/entityframework-entity-proxy-error