不幸的是,你在这里做的是将变量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?
感谢您的答案,我发现并看到类似的克隆实现,我希望会有一块Linq 2 SQL魔术可以帮助我仿照伪问题代码。 – JoeBlogs1999 2010-05-13 04:25:24