[英]An object in the Automapper is returning null
我正在嘗試使用示例示例來映射 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。 我也試過反之亦然,同樣是返回空值。 有人可以幫我解決這個問題嗎?
您缺少CompanyViewItem
和Company
之間的映射配置:
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);
如果你得到mapper.map()
在單元測試中返回null,請確保您不會嘲笑automapper依賴於任何服務正在測試,而是使用真實的東西。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.