Linq to sql,将原实体复制到新实体并保存 [英] Linq to sql, copy original entity to new one and save

查看:16
本文介绍了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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆