0

有没有办法将整个源对象作为一个副本保留在我的目标类中作为属性..

例如

来源:

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 类没有可以帮助我反向映射的默认构造函数。此外,源类位于我无法修改的库中 :( 并且具有接受整个源对象的方法/函数。感谢任何帮助。谢谢。

4

1 回答 1

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);       
    }
}
于 2016-10-04T13:49:10.260 回答