如何使用automapper将另一个类的属性映射到父类?

时间:2014-10-21 07:44:43

标签: automapper automapper-2 automapper-3

我是Automapper的新手。

我有一个domin和ViewModel类。

我想将域类映射到ViewModel类。

域类:

 public class PurchaseOrder
    {
        public int Id { get; set; }
        public string PONo { get; set; }
        public DateTime PODate { get; set; }

        public int CompanyId { get; set; }
    }

    public class Company
    {
        public int Id { get; set; }
        public string Name { get; set; }

    }

查看模型类

 public class PurchaseOrderVM
    {
        public int Id { get; set; }
        public string PONo { get; set; }
        public DateTime PODate { get; set; }

        public int CompanyId { get; set; }
        public string CompanyName { get; set; }


    }

    public class CompanyVM
    {
       public int Id { get; set; }
       public string Name { get; set; }

    }

现在,如果你能看到,我可以完美地映射ID,PONo,PoDate。

但是,我想知道如何将CompanyID和ComapanyName从Domain映射到VM类?

变换方法

static void POTransform()
        {


            PurchaseOrder PODomain = new PurchaseOrder();

            PODomain.Id = 1;
            PODomain.PONo = "154";
            PODomain.PODate = Convert.ToDateTime("5-Jun-2014");

            Mapper.CreateMap<PurchaseOrder, PurchaseOrderVM>()
                .ForMember(dest => dest.CompanyName, Source => Source.MapFrom(????);

        }

1 个答案:

答案 0 :(得分:0)

Mapper.CreateMap<PurchaseOrder, PurchaseOrderVM>()
            .ForMember(dest => dest.CompanyName, opt => opt.MapFrom(src => GetCompanyById(src.CompanyId).Name));
    }


private Company GetCompanyById(int companyId)
    {
        ....
    }