[.net]EF複製一個完整的物件

  • 666
  • 0
  • 2020-07-10

摘要:[.net]複製一個完整的物件

我是把他寫成一個Extension

using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Runtime.Serialization;
using System.Text;


namespace StressTestQueueBot
{
    public static class Extension
    {
        public static Object DataContractSerialization(this Object originalObj)
        {
            DataContractSerializer dcSer = new DataContractSerializer(originalObj.GetType());
            MemoryStream memoryStream = new MemoryStream();

            dcSer.WriteObject(memoryStream, originalObj);
            memoryStream.Position = 0;

            Object newObject = (Object)dcSer.ReadObject(memoryStream);
            return newObject;

        }
    }
}

使用範例像是這樣:

 Input_tx inputTxNew = new Input_tx();
inputTxNew = (Input_tx)iFormal.DataContractSerialization();

 

通常想要用EF做到類似SQL的Insert + select的效果的時候,就會用到這個技巧(特別是你不想寫一個sp執行insert select,然後用ef去執行此sp的時候,就一定會用到本篇的複製)
當然或是你只是想要複製一個物件的時候也可以用

補充:2020/07/10
可利用json.net的序列化功能快速複製,不過前提是此物件必須能夠被序列化跟反序列化喔

var copyObj = JsonConvert.DeserializeObject<YourType>(JsonConvert.SerializeObject(originalObj));

參考文章

Create shallow copy/clone of subclass of EntityObject

http://stackoverflow.com/questions/9695420/create-shallow-copy-clone-of-subclass-of-entityobject