将LINQ to SQL实体复制[克隆]导致数据库中出现新记录的最佳做法是什么?
上下文是我希望为管理员的网格中的记录创建重复的功能。网站,并尝试了一些事情和明显的,读取数据,改变ID = 0,更改名称,submitChanges()
,并命中一个例外,哈哈。我想我可能会停下来问一位专家。
我希望首先阅读记录,通过在“Copy Of”前面添加名称然后另存为新记录来更改名称。
答案 0 :(得分:11)
创建一个新实例,然后将linq映射类与反射一起使用来复制成员值。
E.g。
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克隆它:
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);
}
}
答案 1 :(得分:11)
如果从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();
答案 2 :(得分:3)
我遇到了同样的问题,Kristofer的代码完美无缺,非常感谢!
如果有人感兴趣,我稍微修改了他的代码,这样它就不会接受目标实体作为参数,而是创建一个新对象并返回它。另外,我将sourceEntity
参数设为通用:
public static T CloneEntity<T>(this DataContext dc, T sourceEntity) where T:class, new()
{
var targetEntity = new T();
//... original method code...
return targetEntity;
}
然后我可以做以下事情:
dataContext.MyEntities.Attach(dataContext.CloneEntity(theEntity));
答案 3 :(得分:0)
这是与Peter K.相同的解决方案,用于VB.Net中的Linq-to-Sql Entity Clone。
Dim DC As New DataContext
Dim DCI As New DataContext
DC.ObjectTrackingEnabled = False
Dim RGF As sf_RuleGroup = (From G In DC.sf_RuleGroups _
Where G.RuleGroupID = CInt(e.CommandArgument) _
Select G).First()
DCI.sf_RuleGroups.InsertOnSubmit(RGF)
DCI.SubmitChanges()
答案 4 :(得分:0)
在实体框架6中,您可以执行此操作
Dim WorkoutNew As New Workout 'create a record
ff7db.Workouts.Add(WorkoutNew) 'add it to the table (workout)
ff7db.Entry(WorkoutNew).CurrentValues.SetValues(WorkoutsPost) ' update its values with a class with the same properties