具有通用列表的automapper map类到具有不同泛型的相同类

时间:2015-10-14 14:34:50

标签: c# generics automapper

我有这堂课:

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

我已经在MapUserEntity之间创建了UserDto,但显然我错过了什么?

1 个答案:

答案 0 :(得分:1)

您还需要在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);
}