I\'m working on an EF 5 Code-First solution and I am trying to update an existing entity with a modified one using the Repository pattern:
public void Up
public static T Clone(this T entity) where T : class
{
var type = entity.GetType();
var clone = Activator.CreateInstance(type);
var navigationProperties = type.GetProperties(BindingFlags.GetProperty | BindingFlags.Public | BindingFlags.Instance | BindingFlags.SetProperty | BindingFlags.DeclaredOnly);
foreach (var property in type.GetProperties(BindingFlags.GetProperty | BindingFlags.Public | BindingFlags.Instance | BindingFlags.SetProperty))
{
//if (property.Module.ScopeName == "EntityProxyModule") continue;
if (navigationProperties.Contains(property)) continue;
if (property.CanWrite)
{
property.SetValue(clone, property.GetValue(entity, null), null);
}
}
return (T)clone;
}
Only the navigation properties are defined directly on the dynamic proxy so using BindingFlags.DeclaredOnly will filter them out.
The alternative (commented out) method differentiates the navigation properties using property.Module.ScopeName, for navigation properties this value will be "EntityProxyModule", whereas for the other properties this value will be the dll name of the project you defined the EF code first domain class in.
I use this Clone method to clone EF code first domain objects ready for Json serialization (avoiding circular references), but the author's query as to how to get a list of navigation properties is contained within.