Search code examples
linqentity-framework-5automapper-3

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.

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.


Solution

  • 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