重复的LINQ to SQL实体/记录? [英] Duplicate LINQ to SQL entity / record?
问题描述
什么会被认为是最好的做法,复制[克隆]一个LINQ to SQL的实体,从而在数据库中的新记录?
What would be considered the best practice in duplicating [cloning] a LINQ to SQL entity resulting in a new record in the database?
的背景是,我希望做一个复制功能,记录管理员的网格。网站和尝试一些事情,明显后,读取数据,更改ID = 0,更改名称,的SubmitChanges()
,并创下了异常,大声笑。我想我可能会停下来问专家。
The context is that I wish to make a duplicate function for records in a grid of an admin. website and after trying a few things and the obvious, read data, alter ID=0, change name, submitChanges()
, and hitting an exception, lol. I thought I might stop and ask an expert.
我要开始第一次读记录,改变以副本由prefixing的名称,然后保存为一个新的记录。
I wish to start with first reading the record, altering the name by prefixing with "Copy Of " and then saving as a new record.
推荐答案
创建一个新的实例,然后使用LINQ的映射类以及反射复制成员的值。
Create a new instance and then use the linq mapping classes together with reflection to copy member values.
例如。
public static void CopyDataMembers(this DataContext dc,
object sourceEntity,
object targetEntity)
{
//get entity members
IEnumerable<MetaDataMember> dataMembers =
from mem in dc.Mapping.GetTable(sourceEntity.GetType())
.RowType.DataMembers
where mem.IsAssociation == false
select mem;
//go through the list of members and compare values
foreach (MetaDataMember mem in dataMembers)
{
object originalValue = mem.StorageAccessor.GetBoxedValue(targetEntity);
object newValue = mem.StorageAccessor.GetBoxedValue(sourceEntity);
//check if the value has changed
if (newValue == null && originalValue != null
|| newValue != null && !newValue.Equals(originalValue))
{
//use reflection to update the target
System.Reflection.PropertyInfo propInfo =
targetEntity.GetType().GetProperty(mem.Name);
propInfo.SetValue(targetEntity,
propInfo.GetValue(sourceEntity, null),
null);
// setboxedvalue bypasses change tracking - otherwise
// mem.StorageAccessor.SetBoxedValue(ref targetEntity, newValue);
// could be used instead of reflection
}
}
}
...或者你可以使用DataContractSerializer的克隆它:
...or you can clone it using the DataContractSerializer:
internal static T CloneEntity<T>(T originalEntity) where T : someentitybaseclass
{
Type entityType = typeof(T);
DataContractSerializer ser =
new DataContractSerializer(entityType);
using (MemoryStream ms = new MemoryStream())
{
ser.WriteObject(ms, originalEntity);
ms.Position = 0;
return (T)ser.ReadObject(ms);
}
}
这篇关于重复的LINQ to SQL实体/记录?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!