Linq to sql,将原始实体复制到新实体并保存 [英] Linq to sql, copy original entity to new one and save
本文介绍了Linq to sql,将原始实体复制到新实体并保存的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有一种情况,我不能只更新数据库中的原始记录,而是创建新记录,复制旧字段中的所有字段并将更改应用于新字段. (如果转换为代码,则类似这样)
I have a situation when I cant just update original record in database, but instead make a new record, copy all fields from old and apply changes to new one. (something like this if translated to code)
var original = from _orig in context.Test where _orig.id == 5 select _orig;
Test newTest = new Test();
newTest = original;
newTest.id = 0;
context.Test.InsertOnSubmit(newTest);
context.SubmitChanges();
original.parent_id = newTest.id;
original.isActive = 0;
给出以下异常:
Cannot add an entity that already exists.
是否可以使它工作而无需手动复制每个字段?
Is it possible to make it work without manually copying every field?
推荐答案
这应该有效:
通用Clone()方法
此方法将通过序列化创建任何对象的完整克隆.最初的想法来自此处和此处.
This method will create a full clone of any object by serializing it. The original idea came from both here and here.
/// <summary>
/// Clones any object and returns the new cloned object.
/// </summary>
/// <typeparam name="T">The type of object.</typeparam>
/// <param name="source">The original object.</param>
/// <returns>The clone of the object.</returns>
public static T Clone<T>(this T source) {
var dcs = new DataContractSerializer(typeof(T));
using(var ms = new System.IO.MemoryStream()) {
dcs.WriteObject(ms, source);
ms.Seek(0, System.IO.SeekOrigin.Begin);
return (T)dcs.ReadObject(ms);
}
}
您的代码示例
现在,借助上述扩展方法,只要稍作调整,您的代码就可以正常工作:
Now with the help of the above extension method, your code should work if tweaked a little bit:
var original = from _orig in context.Test where _orig.id == 5 select _orig;
Test newTest = original.Clone();
newTest.id = 0;
context.Test.InsertOnSubmit(newTest);
context.SubmitChanges();
original.parent_id = newTest.id;
original.isActive = 0;
这篇关于Linq to sql,将原始实体复制到新实体并保存的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文