Automapper中的对象返回null

时间:2015-06-05 13:02:00

标签: c# automapper

我正在尝试使用示例示例来映射CustomerViewItem(Source)和Customer(Destination)。

以下是我要映射的源实体

public class CustomerViewItem
{
    public CompanyViewItem companyViewItem { get; set; }
    public string CompanyName { get; set; }
    public int CompanyEmployees { get; set; }
    public string CompanyType { get; set; }
    public string FullName { get; set; }
    public string FirstName { get; set; }
    public string LastName { get; set; }        
    public DateTime DateOfBirth { get; set; }
    public int NumberOfOrders { get; set; }
    public bool VIP { get; set; }
} 

public class Customer
{
    public Company company { get; set; }        
    public string CompanyName { get; set; }
    public int CompanyEmployees { get; set; }
    public string CompanyType { get; set; }
    public string FirstName { get; set; }
    public string LastName { get; set; }
    public DateTime DateOfBirth { get; set; }
    public int NumberOfOrders { get; set; }
    public bool VIP { get; set; }
}

public class Address
{
    public string TempAddress { get; set; }
    public string PermAddress { get; set; }
}

public class Company
{
    public string Name { get; set; }
    public int Employees { get; set; }
    public string Type { get; set; }
    public Address address { get; set; }

}

public class CompanyViewItem
{
    public string Name { get; set; }
    public int Employees { get; set; }
    public string Type { get; set; }
    public Address address { get; set; }
}

现在,对于CustomerViewItem实体,我添加了一些示例值。由于CustomerViewItem中的CompanyViewItem是一个具有类的类,因此我以这种方式添加了值

companyViewItem = new CompanyViewItem() { address = new Address { PermAddress = "pAdd", TempAddress = "tAdd" }, Employees = 15, Name = "name", Type = "abc" }

现在这是我的AutoMapper代码:

Mapper.CreateMap<CustomerViewItem, Customer>();
CustomerViewItem customerViewItem = GetCustomerViewItemFromDB();
Customer customer = Mapper.Map<CustomerViewItem,Customer>customerViewItem);

一切运行正常,但只有公司才能返回null。 我也反过来试过,同样是返回null。 有人可以帮我解决这个问题吗?

1 个答案:

答案 0 :(得分:2)

您缺少CompanyViewItemCompany之间的映射配置:

Mapper.CreateMap<CompanyViewItem, Company>();

您的映射代码应该是:

// Setup
Mapper.CreateMap<CustomerViewItem, Customer>()
      .ForMember(dest => dest.company, opt => opt.MapFrom(src => src.companyViewItem));
Mapper.CreateMap<CompanyViewItem, Company>();

CustomerViewItem customerViewItem = GetCustomerViewItemFromDB();

// Mapping
Customer customer = Mapper.Map<CustomerViewItem,Customer>(customerViewItem);