Automapper with linq how?

天涯浪子 提交于 2019-12-14 02:25:37

问题


Ok, I'm really struggling with finding a good example of what I need to do. So, I'll ask here.

Let's say I have a entity class (EF) named Customer and a corresponding view-model class named CustomerViewModel.

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();
        }
    } 

Thanks in advance.


回答1:


When you register your mappings, you must provide any complex mapping operations that have to occur. In your case, I believe all your properties match up, except for FullName = c.FirstName + " " + c.LastName. Here's how your Customer-to-CustomerViewModel mapping should look:

Mapper.CreateMap<Customer, CustomerViewModel>()
       .ForMember(custVm => custVm.FullName,
            mapper => mapper.MapFrom(cust => cust.FirstName + " " + cust.LastName));

You'll have to figure out how to shove the FullName prop from the ViewModel back into the FirstName & LastName fields on the EF class, though. But when you decide how to implement it, follow the pattern from above for the other mapping.

Your query can now be MUUUCH smaller:

using (var context = new GCSBaseEntities()) 
{
     return from c in context.Customers
            select Mapper.Map<CustomerViewModel>(c);
}



回答2:


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);

I got this from this thread: LINQ and AutoMapper



来源:https://stackoverflow.com/questions/20223995/automapper-with-linq-how

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!