不幸的是,你在這裏做的是將變量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