c# - 使用 AutoMapper 映射类数组

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

我是 AutoMapper 的新手,正在尝试映射 ArrayItemLink[]

public class ViewModel
{
  public ItemLink[] ItemLinks { get; set; }
}

public class ItemLink
{
  public string Description { get; set; }
}

我试过了:

Mapper.Map<viewModel.ItemLink>(db.ItemLinks);

错误:

"Mapper not initialized. Call Initialize with appropriate configuration. If you are trying to use mapper instances through a container or otherwise, make sure you do not have any calls to the static Mapper.Map methods, and if you're using ProjectTo or UseAsDataSource extension methods, make sure you pass in the appropriate IConfigurationProvider instance."

不可以是简单的映射吗?

编辑 1

为了进一步说明,我从数据库中获得了类似的类结构。例子,

public class Db
{
  public ItemLink[] ItemLinks { get; set; }
}

所以,我想将 ViewModel.ItemLink[] 映射到 Db.ItemLink[]

最佳答案

您不能像在 Mapper.Map<viewModel.ItemLink>(db.ItemLinks); 中那样为通用参数提供变量.称为类型参数,必须是类型。

正如@gisek 在他的回答中提到的,您需要先配置映射器。通常它在应用程序启动时完成。

您可以考虑从数据库中获取完整对象,但您也可以选择使用可查询扩展,它只用于获取您的 View 模型所需的数据。

配置。我假设你有命名空间 DB对于数据库中的实体,以及 View View 模型的命名空间。

Mapper.Initialize(cfg => {
    cfg.CreateMap<DB.ItemLink, View.ItemLink>();
});
Mapper.Configuration.AssertConfigurationIsValid();

从数据库中获取完整实体,然后将其映射到属性:

var viewModel = new View.Item();
viewModel.ItemLinks = Mapper.Map<View.ItemLink[]>(db.ItemLinks.ToArray());
从数据库到 View 模型的

项目实体:

var viewModel = new View.Item();
viewModel.ItemLinks = db.ItemLinks.ProjectTo<View.ItemLink>().ToArray();

关于c# - 使用 AutoMapper 映射类数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43561067/

相关文章:

javascript - 修改Kendo UI Dropdownlist的change事件

c# - 简化复杂的 If 语句

c# - 每种角色类型的不同默认页面/ Controller - MVC 5

asp.net - 如何将 Gridview 中的 DropDownList 与不是来自 gridview 的数据绑定(bind)

asp.net - 如何转换类似web.config的log4net配置?

asp.net - 为什么Membership.CreateUser失败?

c# - 使用 Mock.of 的对象的 Moq 返回值?

c# - 传递给存储库方法的表达式未正确编译

javascript - 根据从 SQL Server 数据库中获取的选项隐藏/显示下面的选择

asp.net-mvc - 加载更多按钮和 seo