PRK*_*PRK 2 c# wpf mvvm automapper automapper-6
我有BusinessLayer, DTO library,DataService, EntityModel(wher EDMX sits),DTO库指的是业务层和数据层。我正在尝试在数据层中实现automapper,想要将实体对象映射到 DTO 对象并从dataService库返回 DTO。
目前正在这样做
public class DataService
{
private MapperConfiguration config;
public DataService()
{
IMapper _Mapper = config.CreateMapper();
}
public List<Dto.StudentDto> Get()
{
using(var context = new DbContext().GetContext())
{
var studentList = context.Students.ToList();
config = new MapperConfiguration(cfg => {
cfg.CreateMap<Db.Student, Dto.StudentDto>();
});
var returnDto = Mapper.Map<List<Db.Student>, List<Dto.StudentDto>>(studentList);
return returnDto;
}
}
}
Run Code Online (Sandbox Code Playgroud)
如何将所有映射移至一个类,并且在调用数据服务器时自动映射器应自动初始化?
在数据层使用 AutoMapper 是一个好习惯吗?
是的。
如何将所有映射移至一个类,并且在调用数据服务器时自动映射器应自动初始化?
您可以创建一个静态类来创建一次映射:
public static class MyMapper
{
private static bool _isInitialized;
public static Initialize()
{
if (!_isInitialized)
{
Mapper.Initialize(cfg =>
{
cfg.CreateMap<Db.Student, Dto.StudentDto>();
});
_isInitialized = true;
}
}
}
Run Code Online (Sandbox Code Playgroud)
确保您在数据服务中使用此类:
public class DataService
{
public DataService()
{
MyMapper.Initialize();
}
public List<Dto.StudentDto> GetStudent(int id)
{
using (var context = new DbContext().GetContext())
{
var student = context.Students.FirstOrDefault(x => x.Id == id)
var returnDto = Mapper.Map<List<Dto.StudentDto>>(student);
return returnDto;
}
}
}
Run Code Online (Sandbox Code Playgroud)
根据您实际托管 DAL 的方式,您也许能够Initialize()从可执行文件Main()的方法或从类的构造函数之外的其他位置调用自定义映射器类的方法DataService。