我正在尝试使用自动映射器将数据库表的输出映射到我的类对象。但是该表有3行,它们全部属于单个员工数据,需要将其分配给单个类对象。我们如何创建映射器?是否可以使用此表数据创建映射器?
How can I write Autommapper to populate the class EmployeeDetails
public class EmployeeDetails
{
public string EmpNo { get; set; }
public string Name { get; set; }
public Address Address { get; set; }
public List<Phone> Phone { get; set; }
}
public class Address
{
public string Address_1 { get; set; }
public string City { get; set; }
}
public class Phone
{
public string PhoneType { get; set; }
public string PhoneNo { get; set; }
}
Datatype EmpNo Name Address_1 City PhoneType PhoneNo
Name 1234 Test Test addr Testcity Null Null
Phone 1234 Null Null Null Mobile 123456
Phone 1234 Null Null Null Work 789546
public IEnumerable< EmployeeDetails > GetEmployeeDetails()
{
return ExecuteEmpReader< EmployeeDetails>().ToList();
}
private IEnumerable<T> ExecuteEmpReader <T>()
{
DataTable dt=new Datatable();
//Assume the dt will be loaded as per the above table.
foreach (DataRow item in dt.Rows)
{
yield return _mapper.Map<T>(item)
}
}
答案 0 :(得分:-1)
我不相信有一种方法可以仅使用Automapper来完成您想做的事情。特别是因为行合并为一。该链接显示了如何至少可以将对象平整为所需的对象结构,但是您将需要编写逻辑以自行合并员工地址和电话号码。
http://martinburrows.net/blog/2016/01/18/automatic-unflattening-with-automapper
相反,这会使您将来生成的代码更易于维护。我建议为您的Employee对象创建一些视图,一个用于Employee,一个用于Address,一个用于Phone。然后,您可以使用EF将视图直接映射到对象。