什么被认为是复制[克隆] LINQ to SQL实体导致数据库中新记录的最佳实践?
上下文是我希望为管理员的网格中的记录创建重复的功能.网站和尝试了一些事情和明显的,读取数据后,改变ID = 0,更改名称submitChanges()
,并点击异常,大声笑.我想我可能会停下来问一位专家.
我希望首先阅读记录,通过在"Copy Of"前面添加名称然后另存为新记录来更改名称.
创建一个新实例,然后将linq映射类与反射一起使用以复制成员值.
例如
public static void CopyDataMembers(this DataContext dc, object sourceEntity, object targetEntity) { //get entity members IEnumerabledataMembers = 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克隆它:
internal static T CloneEntity(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); } }
如果从DataContext将实体从ObjectTrackingEnabled加载为false,则可以在另一个DataContext中将此实体作为new插入
DataContext db1 = new DataContext(); DataContext db2 = new DataContext(); db2.ObjectTrackingEnabled = false; MyEntity entToClone = db2.Single(e => e.Id == id); // ... change some data if it is needed db1.MyEntities.InsertOnSubmit(entToClone); db1.SubmitChanges();