我有 NewsViewModel
,其中包括:
public class CategoryViewModel
{
public CategoryViewModel()
{
List = new List<CategoryModel>();
}
public IEnumerable<CategoryModel> List { get; set; }
public CategoryModel CategoryModel { get; set; }
}
ListNews
显示新闻列表;和
NewsModel
用于编辑或插入。
现在我需要使用 automapper
。下面的代码给我一个错误:
public PartialViewResult Edit(int id)
{
var model = new CategoryViewModel();
var cat = _CategoryService.CategoryByID(id);
Mapper.Initialize(cfg => cfg.CreateMap<Category, CategoryModel>());
model.CategoryModel = Mapper.Map<Category, CategoryModel>(cat);
var categorymodel = _CategoryService.GetAllCategory();
Mapper.Initialize(cfg => cfg.CreateMap<Category, IEnumerable<CategoryModel>>());
model.List = Mapper.Map<Category, IEnumerable<CategoryModel>>(categorymodel);
return PartialView(model);
}
我该如何解决这个问题?
最佳答案
如果您有针对这些集合类型的 map ,则无需为这些集合创建新 map 。所以删除这一行:
Mapper.Initialize(cfg => cfg.CreateMap<Category, IEnumerable<CategoryModel>>());
您还试图将单个对象映射到集合。您应该将集合映射到集合:
// move next line to Application_Start
Mapper.Initialize(cfg => cfg.CreateMap<Category, CategoryModel>());
var model = new CategoryViewModel();
var category = _CategoryService.CategoryByID(id);
model.CategoryModel = Mapper.Map<CategoryModel>(category);
var categories = _CategoryService.GetAllCategory();
model.List = Mapper.Map<IEnumerable<CategoryModel>>(categories);
进一步的考虑:
- 使用
Mapper.Map<TDestination>
而不是Mapper.Map<TSource,TDestination>
因为可以从方法参数中推断出源类型 - 使用有意义的变量名称。无需保存几个字符即可使用
cat
而不是category
.和名字categoryModel
只是误导 - 这个变量包含类别列表。 - 最后 - 不要在每次要映射对象时都创建 map 。在应用程序启动时创建一次 map 。
关于c# - 使用自动映射器时无法从 'System.Collections.Generic.IEnumerable<x>' 转换为 'x',我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42341293/