创建EntityObject子类的浅拷贝/克隆
-
13-12-2019 - |
题
我们的数据库中有一个审计表,在更新时,旧值和新值被序列化为XML并存储在同一行中。因此,对象当前是深度克隆的:
public EntityObject CloneEntity(EntityObject obj)
{
DataContractSerializer dcSer = new DataContractSerializer(obj.GetType());
MemoryStream memoryStream = new MemoryStream();
dcSer.WriteObject(memoryStream, obj);
memoryStream.Position = 0;
EntityObject newObject = (EntityObject)dcSer.ReadObject(memoryStream);
return newObject;
}
虽然这是有效的,但由于从深度克隆中提取的相关记录,它生成了大量的数据,并且从数据库中读取了数十万次 dcSer.WriteObject(memoryStream, obj)
, ,最终的内存流大小为200mb,更不用说写回数据库的数据量了。不理想。
所以我想做一个memberwise克隆,因为我的理解是memberwise克隆会将对象引用排除在外,并避免复制所有相关的实体框架模型。
所以我做了这个:
public EntityObject CloneEntity(EntityObject obj)
{
EntityObjectAuditable auditable = (EntityObjectAuditable)obj; // invalid cast exception
return auditable.ShallowCopy();
}
// ....
public class EntityObjectAuditable : EntityObject
{
public EntityObjectAuditable ShallowCopy()
{
return (EntityObjectAuditable)this.MemberwiseClone();
}
}
但是我得到一个无效的强制转换异常,因为传入的实际类型 EntityObject
是与表本身相关的子类。
我也尝试过使用扩展方法访问 MemberwiseClone()
, ,但扩展方法无法访问受保护的方法。
那么,如何创建通用EntityObject的浅副本?
解决方案
我的第一个建议是尝试这个,这与你现在正在做的类似,但对我有用,开销很小:
DataContractSerializationUtils.SerializeToXmlString(Entity, throwExceptions);
另外,我之前已经成功地使用了这种方法,并且没有发现输出太冗长。这和你现在做的差不多。
/// <summary>
/// Creates an exact duplicate of the entity provided
/// </summary>
/// <param name="source">The source copy of the entity</param>
/// <returns>An exact duplicate entity</returns>
public TEntity Clone(TEntity Source)
{
// Don’t serialize a null object, simply return the default for that object
if (ReferenceEquals(Source, null))
{
return default(TEntity);
}
var dcs = new DataContractSerializer(typeof (TEntity));
using (Stream stream = new MemoryStream())
{
dcs.WriteObject(stream, Source);
stream.Seek(0, SeekOrigin.Begin);
return (TEntity) dcs.ReadObject(stream);
}
}
如果这两个选项都没有吸引力,我的建议是编写一个简短的函数,使用反射从源实体复制任何属性。
其他提示
从:
http://www.codeproject.com/Tips/474296/Clone-an-Entity-in-Entity-Framework-4.
它更有效,更快,然后序列化-正是你正在寻找的!基本上,它使用反射将必要的属性复制到相同类型的新EntityObject,并且能够通过使用泛型对从EntityObject派生的任何类执行此操作。
public static T CopyEntity<T>(MyContext ctx, T entity, bool copyKeys = false) where T : EntityObject
{
T clone = ctx.CreateObject<T>();
PropertyInfo[] pis = entity.GetType().GetProperties();
foreach (PropertyInfo pi in pis)
{
EdmScalarPropertyAttribute[] attrs = (EdmScalarPropertyAttribute[])pi.GetCustomAttributes(typeof(EdmScalarPropertyAttribute), false);
foreach (EdmScalarPropertyAttribute attr in attrs)
{
if (!copyKeys && attr.EntityKeyProperty)
continue;
pi.SetValue(clone, pi.GetValue(entity, null), null);
}
}
return clone;
}
例如,假设你有一个实体:具有导航属性的客户:命令。然后,您可以使用上述方法复制客户及其订单,如下所示:
Customer newCustomer = CopyEntity(myObjectContext, myCustomer, false);
foreach(Order order in myCustomer.Orders)
{
Order newOrder = CopyEntity(myObjectContext, order, true);
newCustomer.Orders.Add(newOrder);
}
现在的价值呢。EF6中的ToObject()?
var shallowCopy = (TEntity)_dbContext.Entry(entity).CurrentValues.ToObject();