2010-04-23 27 views
2

我有幾個子表項目實體項目的快照(克隆),例如ProjectAwards ProjectTeamMember以使用LINQ 2的Sql

我想從項目(和子表)中的數據複製到一個新項目記錄並更新項目狀態。

var projectEntity = getProjectEntity(projectId); 

draftProjectEntity = projectEntity 
draftProjectEntity.Status = NewStatus 

context.SubmitChanges(); 

我發現這個鏈接from Marc Gravell

其一部分的方式存在,但它更新子記錄新draftProject,我需要它來複制。

回答

1

不幸的是,你在這裏做的是將變量draftProjectEntity設置爲對projectEntity對象的引用。也就是說,他們現在指向同一個對象。你需要做的是深層克隆projectEntity

There are ways of doing this with Reflection - 如果你打算做很多事情 - 那我強烈建議你看看這個方法。

但是,如果你只打算一個層次深,或只爲對象的一個​​小圖,那麼它可能是值得只是做手工,並在你的實體實現自己的IDeepCloneable ...

public interface IDeepCloneable<T> 
{ 
    T DeepClone(); 
} 

public class Person : IDeepCloneable<Person> 
{ 
    public string Name { get; set; } 
    public IList<Address> Addresses { get; set; } 

    public Person DeepClone() 
    { 
     var clone = new Person() { Name = Name.Clone().ToString() }; 

     //have to make a clone of each child 
     var addresses = new List<Address>(); 
     foreach (var address in this.Addresses) 
      addresses.Add(address.DeepClone()); 

     clone.Addresses = addresses; 
     return clone; 
    } 
} 

public class Address : IDeepCloneable<Address> 
{ 
    public int StreetNumber { get; set; } 
    public string Street { get; set; } 
    public string Suburb { get; set; } 

    public Address DeepClone() 
    { 
     var clone = new Address() 
         { 
          Street = this.Street.Clone().ToString(), 
          StreetNumber = this.StreetNumber, //value type - no reference held 
          Suburb = this.Suburb.Clone().ToString() 
         }; 
     return clone; 
    } 
} 

//usage: 
var source = personRepository.FetchByName("JoeBlogs1999"); 
var target = source.DeepClone(); 

//at this point you could set any statuses, or non cloning related changes to the copy etc.. 

targetRepository.Add(target); 
targetRepository.Update; 

有關爲什麼我不使用ICloneable接口的信息...檢查此線程:Should I provide a deep clone when implementing ICloneable?

+0

感謝您的答案,我發現並看到類似的克隆實現,我希望會有一塊Linq 2 SQL魔術可以幫助我仿照僞問題代碼。 – JoeBlogs1999 2010-05-13 04:25:24