我想深入复制一个实体,我正在寻找最好的方法。我也很关心表演。
我计划让我的所有实体都实现ICloneable,Clone()基本上会影子复制并克隆所有引用。
例如:
[DataContract()]
class MyEntity {
public int id;
public string name;
public EntitySet<AnotherEntity> myOtherEntity;
}
MyEntity Clone() {
Entity ent = new Entity();
ent.name = this.name;
ent.myOtherEntity = this.myOtherEntity.Clone();
return ent;
}
这是一个好方法吗?或者我应该使用linq加载实体,删除所有主键(将id设置为0)然后使用Create(实体)函数来复制它?反射是否也是一个有效的解决方案(不是太慢)?至少反射可以在更新我的实体类(例如新成员)时避免出现问题,而无需更新克隆函数...
答案 0 :(得分:0)
ICloneable不是坏解决方案;毕竟,它是为此目的而设计的。我不确定我是否想为每个实体类型编写实现,但是你可以使用代码生成器解决这个问题。但要小心但循环引用。但是,当你这样做时,如果你完全关心性能,你可能会经常这样做。如果性能在这里是一个问题,我想知道你实际上想要解决的问题。
答案 1 :(得分:0)
您可以尝试此功能:
private static object CloneObject(object obj)
{
Type cloneType = obj.GetType();
object clone = Activator.CreateInstance(cloneType);
PropertyInfo[] properties = cloneType.GetProperties(BindingFlags.Public | BindingFlags.Instance | BindingFlags.SetProperty);
foreach (PropertyInfo property in properties)
{
if (property.CanWrite)
{
object value = property.GetValue(obj, null);
property.SetValue(clone, value, null);
}
}
return clone;
}
和
Entity newEnt = new Entity();
newEnt = (Entity)CloneObject(oldEnt);