有没有办法将整个源对象作为副本保存在目标类中作为属性..
e.g。
来源:
class SourceClass
{
prop string Prop1 { get; set; }
prop string Prop2 { get; set; }
}
目的地:
class DestinationClass
{
prop string Prop1 { get; set; }
prop string Prop2 { get; set; }
prop SourceClass SourceClassCopy { get; set; }
}
并使用像
这样的自动播放器配置AutoMapper.Mapper.Initialize(cfg => {
cfg.ReplaceMemberName("this", "SourceClassCopy");
cfg.CreateMap<SourceClass, DestinationClass>(); //or .ForMember("SourceClassCopy", d => d.MapFrom(s => s));
});
为什么我这样做是因为我有一个分层对象,并希望保留一个副本用于反向映射,因为Source类没有一个默认的构造函数来帮助我反向映射。此外,源类位于我无法修改的库中:(并且具有接受整个源对象的方法/函数。感谢任何帮助。谢谢。
答案 0 :(得分:0)
你可以这样做:
public class SourceClass
{
public string Prop1 { get; set; }
public string Prop2 { get; set; }
}
public class DestinationClass
{
public string Prop1 { get; set; }
public string Prop2 { get; set; }
public SourceClass SourceClassCopy { get; set; }
}
public class Program
{
public void Main()
{
var source = new SourceClass();
source.Prop1 = "Prop1Source";
source.Prop2 = "Prop2Source";
var destination = new DestinationClass();
destination.Prop1 = "Prop1Dest";
destination.Prop2 = "Prop2Dest";
var sourceinDest = new SourceClass();
sourceinDest.Prop1 = "Prop1sourceinDest";
sourceinDest.Prop2 = "Prop2sourceinDest";
destination.SourceClassCopy = sourceinDest;
// Configure AutoMapper
Mapper.CreateMap<SourceClass, DestinationClass>()
.ForMember(dest => dest.SourceClassCopy, m=>m.MapFrom(src=>src));
Mapper.Map<SourceClass, DestinationClass>(source, destination);
Console.WriteLine(destination.Prop1);
Console.WriteLine(destination.Prop2);
Console.WriteLine(destination.SourceClassCopy.Prop1);
Console.WriteLine(destination.SourceClassCopy.Prop2);
}
}