AutoMapper 奇怪的错误

AutoMapper strange error

我在 MVC 5 中使用 AutoMapper 4.1.1,然后使用它将实体从 EF6(具有任何虚拟且无延迟加载的纯 Poco)映射到 viewModel。我遇到了一个奇怪的问题,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.

上抛出以下错误

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

映射类型: 人 -> PersonDetailViewModel MyProject.Dto.Person -> MyProject.Website.ViewModels.PersonDetailViewModel

目标路径: IEnumerable`1[0]

源值: MyProject.Dto.Person

您需要return一个列表<> - pagedPersons.ListOfPersons.ToList()

尝试

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