I am attempting a Generic Deep Clone Routine for code first Entity Framework entities.
I've cracked it for the standard System property types but am having trouble with Proxy Entities (defined with virtual) i.e.
[EntityLookup]
public virtual Person { get; set; }
[EntityLookup] is one of my own attributes that helps further define the Association.
If I remove the "virtual" keyword, my routine can update the destination entity property no problem (but I lose the additional EF functionality) With virtual I get the following error;
System.Reflection.TargetException: 'Object does not match target type.'
I believe it's all to do with EF's Proxy class but I'm not sure how to cast the original entity so I can set it on the destination. Below are the essentials of the Clone routine for this issue;
public static void CloneProperties<T>(T Original, T Destination)
{
PropertyInfo[] props = Original.GetType().GetProperties();
foreach (var propertyInfo in props)
{
if (propertyInfo.PropertyType.Namespace == "System" || propertyInfo.PropertyType.IsEnum)....
else
{
if (Destination.PropertyHasCustomAttribute (propertyInfo.Name, typeof(EntityLookupAttribute)))
{
var pv = propertyInfo.GetValue(Original, null);
propertyInfo.SetValue(Destination, pv, null);
}
}
}
}
It's the "propertyInfo.SetValue(Destination, pv, null);" that generates the error when the entity is declared virtual.
Any help on getting it to work will be gratefully accepted
Best Regards
Lance
Aucun commentaire:
Enregistrer un commentaire