Duplicate LINQ to SQL entity / record?

前端 未结 5 865
傲寒
傲寒 2021-01-02 02:35

What would be considered the best practice in duplicating [cloning] a LINQ to SQL entity resulting in a new record in the database?

The context is that I wish to mak

5条回答
  •  -上瘾入骨i
    2021-01-02 02:58

    I was stuck with the same problem and Kristofer's code worked perfectly, many thanks!

    In case someone is interested, I slightly modified his code so that instead of accepting the target entity as a parameter, it creates a new object and returns it. Also I have made the sourceEntity parameter to be generic:

     public static T CloneEntity(this DataContext dc, T sourceEntity) where T:class, new()
     {
         var targetEntity = new T();
         //... original method code...
         return targetEntity;
     }
    

    Then I can do the following:

    dataContext.MyEntities.Attach(dataContext.CloneEntity(theEntity));
    

提交回复
热议问题