2010-04-23 72 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