简体   繁体   English

使用 AutoMapper 映射嵌套的 Class 属性和基础 Class

[英]Use AutoMapper for mapping Nested Class Property along with Base Class

How can I Map Nested Classes using AutoMapper in c#,如何在 c# 中使用 AutoMapper Map 嵌套类,

I am having Classes like..我正在上课,例如..

public class Source{
public int Id {get;set;}
public Address Address {get;set;}
}

public class Dest{
public int Id {get;set;}
public AddressModel Address {get;set;}
}

How can I map Source And Dest class with Address and AddressModel Mapped I am new to AutoMapper Please Help...我如何使用映射地址和地址模型的 map SourceDest class 我是 AutoMapper 的新手,请帮助...

My Mapping Looks as below right now.我的映射现在如下所示。

CreateMap<Source,Dest>().ForMember(dest=>dest.AddressModel,opt=>opt.MapFrom(src=>src.Address)).ReverseMap();

Automapper automatically maps child properties if both source and destination have same name of the child properties ie如果源和目标具有相同的子属性名称,则 Automapper 会自动映射子属性,即

public class Source
    {
        public int Id { get; set; }
        public Address Address { get; set; }
    }

    public class Dest
    {
        public int Id { get; set; }
        public AddressModel Address { get; set; }
    }

    public class Address
    {
        public string Name { get; set; }
    }

    public class AddressModel
    {
        public string Name { get; set; }
    }

Mapping映射

CreateMap<Source, Dest>().ReverseMap();

UseCase用例

var source = new Source { Id = 1, Address = new Address { Name = "A" } };
var dest = _mapper.Map<Dest>(source);

Here you will get address object in dest variable在这里,您将在dest变量中获得地址 object

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM