AutoMapper奇怪的错误

时间:2017-02-02 00:11:02

标签: asp.net asp.net-mvc model-view-controller automapper automapper-4

我在MVC 5中使用AutoMapper 4.1.1,然后使用它将EF6中的实体(任何虚拟和无延迟加载的纯Poco)映射到viewModels。我有一个奇怪的问题,AutoMapper正在正确地进行翻译,但在另一个例子中失败了。

Dto.Person
{
    public int PersonId { get; set; }
    public string Name { get; set; }
    public string Address { get; set; }
    public string Phone { get; set; }
}

ViewModel.PersonDetailViewModel
{
    public int PersonId { get; set; }
    public string Name { get; set; }
    public string Address { get; set; }
    public string Phone { get; set; }
}

public class PagedPersons
{
    public int TotalNumberOfRecords { get; set; }
    public IEnumerable<Person> ListOfPersons { get; set; }
}

获取人员的功能

public IEnumerable<Person> GetAllPersons_NOPaging()
{
    IEnumerable<Person> persons = new List<Person>();
    persons = GetFromdatabase();
    return persons;
}

public PagedPersons GetAllPersons_WithPaging()
{
    int totalNumberOfRecords = 0;
    IEnumerable<Person> = GetFromDatabase();
    return new PagedPersons { TotalNumberOfRecords = totalNumberOfRecords, ListOfPersons = listofPersons };
}

控制器

var pagedPerson = GetAllPersons_WithPaging();
var persons = GetAllPersons_NOPaging();

AutoMapper.Mapper.CreateMap<Person, PersonDetailViewModel>();

// THROWS AN ERROR
var viewModel_1 = AutoMapper.Mapper.Map<IEnumerable<Person>, IEnumerable<PersonDetailViewModel>>(pagedPersons.ListOfPersons);

// does NOT throw error
var viewModel_2 = AutoMapper.Mapper.Map<IEnumerable<Person>, IEnumerable<PersonDetailViewModel>>(persons);

所以,我无法理解我做错了什么,因为AutoMapper能够在viewmodel_2的情况下正确映射,但在viewModel_1上抛出以下错误。

缺少类型映射配置或不支持的映射。

映射类型: 人 - &gt; PersonDetailViewModel MyProject.Dto.Person - &gt; MyProject.Website.ViewModels.PersonDetailViewModel

目的地路径: IEnumerable`1 [0]

来源价值: MyProject.Dto.Person

2 个答案:

答案 0 :(得分:1)

您需要返回一个List&lt;&gt; - pagedPersons.ListOfPersons.ToList()

答案 1 :(得分:-1)

var viewModel_1 = AutoMapper.Mapper.Map<IEnumerable<Person>, IEnumerable<PersonDetailViewModel>>(pagedPersons.ListOfPersons.ToList());