AutoMapper 可查询扩展 ProjectTo 子对象/属性 扩展不起作用

AutoMapper Queryable Extension ProjectTo Child object / Property expansion not working

我是 AutoMapper 的新手,正在尝试使用 ProjectTo 扩展,但我想我遗漏了一些东西。

例如,我创建了一个简单的 AspNetCore 项目来进行测试。 在 Startup.cs ConfigureServices.

中配置 AutoMapper
services.AddAutoMapper(this.GetType().Assembly);

我有这些型号 类:

public class PersonDTO
{
    public string Name { get; set; }
    public string AddressStreetName { get; set; }
    public string AddressStreetNumber { get; set; }
    public string AddressCityName { get; set; }
}

public class Address
{
    public string StreetName { get; set; }
    public string StreetNumber { get; set; }
    public string CityName { get; set; }
}

public class Person
{
    public string Name { get; set; }
    public Address Address { get; set; }
}

然后我也创建了这个配置文件:

public class PersonProfile : Profile
{
    public PersonProfile()
    {
        CreateMap<Person, PersonDTO>().ReverseMap();
    }
}

然后创建 DTO:

var personDTO = new PersonDTO()
{
    Name = "John",
    AddressStreetName = "TestStraat",
    AddressStreetNumber = "10",
    AddressCityName = "TestCity"
};

使用映射器效果很好:

var personFromPersonDTO = _mapper.Map<Person>(personDTO);

地址 属性 已设置。

使用 ProjectTo:

var list = new List<PersonDTO>();
    list.Add(personDTO);
    var listPersons = list
        .AsQueryable()
        .ProjectTo<Person>(_mapper.ConfigurationProvider, m=>m.Address)
        .ToList();

对象已映射到新列表中,但地址 属性 为空。 我在这里错过了什么?

使用ProjectTo时,需要进行一些类型匹配。可以参考这个例子。

    public IActionResult Index()
    {
        var personDTO = new PersonDTO()
        {
            Name = "John",
            AddressStreetName = "TestStraat",
            AddressStreetNumber = "10",
            AddressCityName = "TestCity"
        };
        var personFromPersonDTO = mapper.Map<Person>(personDTO);
        var list = new List<PersonDTO>();
        list.Add(personDTO);
     
        //Configure mapping relationship
        var configuration = new MapperConfiguration(cfg =>
        cfg.CreateMap<PersonDTO, Person>()
        .ForMember(p => p.Name, conf => conf.MapFrom(ol => ol.Name))
        .ForMember(p => p.Address, conf => conf.MapFrom(o => new Address
        {
            CityName = o.AddressCityName,
            StreetName = o.AddressStreetName,
            StreetNumber = o.AddressStreetNumber
        }))
        );
        var modelList=list.AsQueryable().ProjectTo<Person>(configuration);
        return Ok(modelList);
    }

会得到结果