我第一次尝试使用AutoMapper并遇到一些问题。 我的代码在下面,我得到以下错误。也许有人可以展示如何映射模型列表?
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;
}
答案 0 :(得分:3)
在LINQ查询中,选择一个匿名对象。确保选择的是您的源类型的产品(或更具体地说是IEnumerable<Product>
):
IEnumerable<Product> products = _repository.GetProducts(true);
IEnumerable<ProductViewModel> productsViewModel = Mapper.Map<IEnumerable<Product>, IEnumerable<ProductViewModel>>(products);
return View(productsViewModel);
也不要在控制器操作中调用Mapper.CreateMap<TSource, TDest>
。必须在AppDomain的生命周期内仅调用一次,最好是在Application_Start
中。
还要注意我已经摆脱了ViewData,这是一件好事。您不需要ViewData。您正在使用视图模型。这就是他们应该做的。包含视图以强类型方式所需的信息。