我是 AutoMapper 的新手,正在尝试映射 Array
类 ItemLink[]
。
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/