Tomas
Tomas

Reputation: 18127

AutoMapper mapping model list

I am trying to use AutoMapper for the first time and have some problems with it. My code is below and I get error below. Maybe someone could show how to map the list of models?

cannot convert from 'System.Linq.IQueryable<AnonymousType#1>' to 'Entity.Product'   C:\Users\Administrator\Projects\PC\trunk\PC\Controllers\AdminController.cs  37  100 PC
public class ProductViewModel
{
    public int Id { get; set; }
    public string Name { get; set; }
    public int UsersCount { get; set; }
}

var products = _repository.GetProducts(true).Select(p=> new 
{
    p.Id,
    p.Name,
    UsersCount = 0
});

Mapper.CreateMap<Product, ProductViewModel>();
ViewData["Products"] = Mapper.Map<IEnumerable<Product>, IEnumerable<ProductViewModel>>(products); //Error appears on products object


//Product domain model(linq2sql generated model)
public partial class Product : INotifyPropertyChanging, INotifyPropertyChanged
{
    private static PropertyChangingEventArgs emptyChangingEventArgs = new PropertyChangingEventArgs(String.Empty);
    private int _Id;
    private bool _Active;
    private System.Nullable<int> _Sort;
    private System.Nullable<int> _Category;
    private string _Name;
    private int _ProductTypeId;
    private decimal _Price;
    private System.Nullable<int> _Months;
    private System.Nullable<int> _Credits;
    private string _Features;
    private string _BlockReason;
    private string _BuyUrl1;
    private string _BuyUrl2;
    private bool _UsersManager;
}

Upvotes: 0

Views: 1030

Answers (1)

Darin Dimitrov
Darin Dimitrov

Reputation: 1039578

In your LINQ query you select an anonymous object. Make sure you select a Product which is your source type (or more specifically IEnumerable<Product>):

IEnumerable<Product> products = _repository.GetProducts(true);
IEnumerable<ProductViewModel> productsViewModel = Mapper.Map<IEnumerable<Product>, IEnumerable<ProductViewModel>>(products);
return View(productsViewModel);

Also do not call Mapper.CreateMap<TSource, TDest> inside your controller action. This must be called only once in the lifetime of the AppDomain, ideally in your Application_Start.

Also notice that I have gotten rid of ViewData which is a great thing. You don't need ViewData. You are working with view models. That's what they are supposed to do. Contain information that will be needed by your view in a strongly typed manner.

Upvotes: 3

Related Questions