自动映射器将具有泛型列表的类映射到具有不同泛型的相同类
本文关键字:泛型 映射 同类 列表 | 更新日期: 2023-09-27 18:17:52
我有这样一个类:
public class PagedListResult<T>
{
public int RecordCount {get; set;}
public int PageNumber {get; set;}
public int PageSize {get; set;}
public IEnumerable<T> Records {get; set;}
}
现在我想创建映射器将我的EF
实体映射到我的Dto
模型,例如:
public class UserEntity
{
public int Id {get; set;}
public string Name {get; set;}
}
public class UserDto
{
public int Id {get; set;}
public string Name {get; set;}
}
在我的BLL
类:
//other code
PagedListResult<UserEntity> result = _repo.GetUsers();
var pagedListOfDtos = Mapper.Map<PagedListResult<UserDto>>(result);
return pagedListOfDtos;
//other code
我已经在UserEntity
和UserDto
之间创建了Map
,但显然我错过了什么?
您还需要创建PagedListResult<UserEntity>
和PagedListResult<UserDto>
之间的映射,然后这个测试通过:
[SetUp]
public void Setup()
{
Mapper.CreateMap<UserEntity, UserDto>();
Mapper.CreateMap<PagedListResult<UserEntity>, PagedListResult<UserDto>>();
}
[Test]
public void Q33128288()
{
PagedListResult<UserEntity> result = new PagedListResult<UserEntity>
{
Records = new List<UserEntity> {new UserEntity {Id = 7}},
RecordCount = 1
};
var pagedListOfDtos = Mapper.Map<PagedListResult<UserDto>>(result);
Assert.AreEqual(1, pagedListOfDtos.RecordCount);
Assert.AreEqual(1, pagedListOfDtos.Records.Count());
Assert.IsInstanceOfType(typeof(UserDto), pagedListOfDtos.Records.Single());
Assert.AreEqual(7, pagedListOfDtos.Records.Single().Id);
}