好吧,我真的很难找到一个我需要做什么的好例子。所以,我会在这里问。
假设我有一个名为Customer的实体类(EF)和一个相应的名为CustomerViewModel的视图模型类。
使用AutoMapper,我创建了以下映射:
Mapper.CreateMap<CustomerViewModel, Customer>();
Mapper.CreateMap<Customer, CustomerViewModel>();
我将如何修改以下代码以利用此映射?
public static List<CustomerViewModel> GetCustomers()
{
using (var context = new GCSBaseEntities())
{
var query = from c in context.Customers
select new CustomerViewModel
{
CompanyName = c.CompanyName,
Id = c.Id,
EmailAddress = c.EmailAddress,
FirstName = c.FirstName,
LastName = c.LastName,
MiddleName = c.MiddleName,
ModifiedDate = c.ModifiedDate,
Phone = c.Phone,
SalesPerson = c.SalesPerson,
Suffix = c.Suffix,
Title = c.Title,
FullName = c.FirstName + " " + c.LastName
};
return query.ToList();
}
}
提前谢谢。
注册映射时,必须提供任何必须发生的复杂映射操作。在您的情况下,我相信除了FullName = c.FirstName + " " + c.LastName
之外,您的所有属性都匹配。以下是客户到客户视图模型映射的样子:
Mapper.CreateMap<Customer, CustomerViewModel>()
.ForMember(custVm => custVm.FullName,
mapper => mapper.MapFrom(cust => cust.FirstName + " " + cust.LastName));
您必须弄清楚如何将FullName
道具从ViewModel推回到FirstName
&不过,EF类上的LastName
字段。但是,当您决定如何实现它时,请按照上面的模式进行其他映射。
您的查询现在可以缩小MUUUCH:
using (var context = new GCSBaseEntities())
{
return from c in context.Customers
select Mapper.Map<CustomerViewModel>(c);
}
想明白了。为了避免上述错误,您必须在Customers:之后添加对.AsEnumerable()的调用
return from c in context.Customers.AsEnumerable()
select Mapper.Map<CustomerViewModel>(c);
我从这个线程得到了这个:LINQ和AutoMapper