带有linq的Automapper如何? [英] Automapper with linq how?
问题描述
好的,我真的很难找到我需要做的很好的例子.所以,我会在这里问.
Ok, I'm really struggling with finding a good example of what I need to do. So, I'll ask here.
比方说,我有一个名为Customer的实体类(EF)和一个名为CustomerViewModel的对应视图模型类.
Let's say I have a entity class (EF) named Customer and a corresponding view-model class named CustomerViewModel.
使用AutoMapper,我创建了以下映射:
Using AutoMapper, I have created the following mappings:
Mapper.CreateMap<CustomerViewModel, Customer>();
Mapper.CreateMap<Customer, CustomerViewModel>();
我将如何修改以下代码以利用此映射?
How would I modify the following code to make use of this mapping?
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();
}
}
先谢谢了.
推荐答案
弄清楚了.为了避免上述错误,您必须在客户之后添加调用.AsEnumerable(),如下所示:
Figured it out. In order to avoid the aforementioned error, you have to Add the call the .AsEnumerable() after Customers like so:
return from c in context.Customers.AsEnumerable()
select Mapper.Map<CustomerViewModel>(c);
我是通过以下线程得到的: LINQ和AutoMapper
I got this from this thread: LINQ and AutoMapper
这篇关于带有linq的Automapper如何?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!