Automapper 中的对象返回 null

Viv*_*vek 1 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; }
}
Run Code Online (Sandbox Code Playgroud)

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

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

现在这是我的 AutoMapper 代码:

Mapper.CreateMap<CustomerViewItem, Customer>();
CustomerViewItem customerViewItem = GetCustomerViewItemFromDB();
Customer customer = Mapper.Map<CustomerViewItem,Customer>customerViewItem);
Run Code Online (Sandbox Code Playgroud)

一切都运行良好,但只有公司返回 null。我也试过反之亦然,同样是返回空值。有人可以帮我解决这个问题吗?

Ros*_*oss 7

如果您mapper.map()在单元测试中返回 null,请确保您没有模拟自动映射器对您正在测试的任何服务的依赖关系,而是使用真实的东西。


rag*_*eit 5

您缺少CompanyViewItem和之间的映射配置Company

Mapper.CreateMap<CompanyViewItem, Company>();
Run Code Online (Sandbox Code Playgroud)

您的映射代码应该类似于:

// 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);
Run Code Online (Sandbox Code Playgroud)