我正在使用Entity Framework的Code First开发。问题是:在克隆延迟加载列表时,列表元素类型为:
因为我只需要复制特定深度的内容,所以我不能序列化整个树形结构,然后再反序列化它。
我的模型是:
System.Data.Entity.DynamicProxies.Node_CB2936E7A8389F56009639CD3D732E4B509C4467531A6AFB3A143429D77A07DF
,而我的通用函数将其视为System.Object
。有没有办法在将它们传递给Clone
函数之前将此对象转换为其父类?或者有其他想法吗?因为我只需要复制特定深度的内容,所以我不能序列化整个树形结构,然后再反序列化它。
我的模型是:
public class Node
{
public int Id { get; set; }
public String Name { get; set; }
public virtual IList<Node> Nodes { get; set; }
public int? ParentId { get; set; }
[ForeignKey("ParentId")]
public virtual Node Parent { get; set; }
}
使用函数进行克隆:
protected T Clone<T>(T entity, int depth) where T : new()
{
var cloned = new T();
foreach (var property in cloned.GetType().GetProperties())
{
if (property.PropertyType.Namespace == "System" && property.CanWrite)
{
property.SetValue(cloned, property.GetValue(entity));
}
else if (depth > 0 && property.CanWrite)
{
if (property.PropertyType.Namespace == "System.Collections.Generic")
{
var type = property.PropertyType.GetGenericArguments()[0];
Type genericListType = typeof(List<>).MakeGenericType(type);
var collection = (IList)Activator.CreateInstance(genericListType);
var value = property.GetValue(entity);
foreach (var element in value as IEnumerable)
{
collection.Add(Clone(element, depth - 1)); // here is Error:
//The value “System.Object” is not of type “Sandbox.Models.Node” and cannot be used in this generic collection. Parameter name: value
//I should cast element to its parent class but how?
}
property.SetValue(cloned, collection);
}
}
}
return cloned;
}
这个函数在非实体框架对象上运作得很好。
Clone
函数的使用方法如下:
var cloned = Clone(context.Nodes.Find(10), 2);
需要帮助请告知。