如何使用包含一个AutoMapper IList的财产深克隆对象 [英] How to deep clone objects containing an IList property using AutoMapper
问题描述
我想深克隆使用AutoMapper以下类:
I am trying to deep clone the following class using AutoMapper:
public class MainData
{
public MainData()
{
Details = new List<Detail>();
}
public int Id { get; private set; }
public DateTime LastUpdate { get; private set; }
public IList<Detail> Details { get; private set; }
public int Prop1 { get; set; }
public int Prop2 { get; set; }
public void AddDetail(Detail detail)
{
Details.Add(detail);
}
public void RemoveDetail(Detail detail)
{
Details.Remove(detail);
}
public MainData Clone()
{
Mapper.Reset();
Mapper.CreateMap<MainData, MainData>().ForMember(d => d.Id, o => o.Ignore());
// Mapper.CreateMap<Detail, Detail>().ForMember(d => d.Id, o => o.Ignore()); // REMOVED
var newMainData = new MainData();
Mapper.Map(this, newMainData);
newMainData.Details = this.Details.Select(item => item.Clone()).ToList(); // ADDED
return newMainData;
}
}
public class Detail
{
public int Id { get; private set; }
public string Name { get; set; }
public double Area { get; set; }
public double Height { get; set; }
public Detail Clone() // ADDED
{
Mapper.CreateMap<Detail, Detail>().ForMember(d => d.Id, o => o.Ignore());
var newDetail = new Detail();
Mapper.Map(this, newDetail);
return newDetail;
}
}
的
克隆
办法正常工作的MainData性能,但似乎只能做详细列表的浅表副本。我曾尝试加入 .ForMember(D => d.Details,O => o.UseDestinationValue())
但是,这并不在所有复制的详细列表。 ?我怎样才能得到详细信息列表深克隆以及即,所以我结束了两个完全独立的对象包括所有的列表项
The Clone
method works fine for the MainData properties but seems to only do a shallow copy of the Details list. I have tried adding .ForMember(d => d.Details, o => o.UseDestinationValue())
but this does not copy the Details list at all. How can I get the Details list deep cloned as well ie, so I end up with two totally independent objects including all the list items?
更新:。STRONG>我需要排除,因为我使用与NHibernate这些对象,因此不能肯定是否可序列化解决方案将做到这一点Id属性。
UPDATE: I need to exclude the Id property as I am using these objects with NHibernate so not sure if the Serializable solution will do this.
UPDATE2:修改了上面的代码克隆的IList了。这似乎很好地工作,因为我可以排除,使NHibernate的认为它已经保存的属性。
UPDATE2: Modified the above code to clone the IList too. This seems to work fine as I can exclude properties that make NHibernate think it has already been saved.
推荐答案
下面是一个解决方案与 ValueInjecter
here is one solution with the ValueInjecter
var clone = new MainData();
clone.InjectFrom(mainData);//mainData is your source
mainData.Details.AsParallel.ForAll(detail =>
{
var dc = new Detail();
dc.InjectFrom(detail);
clone.AddDetail(dc);
});
这有私人制定者都不会设置属性,(看起来合理)
好运;)
the properties that have private setters are not going to be set, (looks reasonable)
good luck ;)
编辑:
我做了一个更好的解决方案看的这里
这篇关于如何使用包含一个AutoMapper IList的财产深克隆对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!