c# - 使用自动映射器时无法从 'System.Collections.Generic.IEnumerable<x>' 转换为 'x'

标签 c# asp.net asp.net-mvc c#-4.0 automapper

我有 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/

相关文章:

c# - Visual Studio 2013 不发现单元测试

c# - MVVM WPF Multibinding 不适用于命令参数

c# - 在 MVC 中使用GenerateEmailConfirmationTokenAsync 外部 Controller 时出现无效 token

c# - Web API 服务 - 如何使服务器上的请求并发执行

c# - 动态设置属性 WPF 应用程序

c# - 加载表单时自动执行

c# - 从 HTML 生成 Excel 文件

asp.net - 将下拉列表的选定值传递给参数

c# - 在 MVC 应用程序中使用 powershell 从 IIS 获取虚拟目录

asp.net-mvc - HttpResponseMessage 内容不会显示 PDF