为什么AutoMapper不使用ProjectTo映射第二级导航属性?

时间:2019-08-05 15:40:42

标签: c# asp.net-core automapper

我有这个简单的课程

public class Store {
    public int Id { get; set; }

    //Other properties

    [JsonIgnore]
    public ICollection<Product> Products { get; set; }
}

和我的DTO

public class StoreDetails {
    public int Id { get; set; }

    //Other properties

    public ICollection<Product> Products { get; set; }
}

和我的Product类:

public class Product {
    public int? Id { get; set; }

    //Other properties

    public ICollection<ProductAttribute> ProductAttributes { get; set; }
}

我的映射如下:

var storeDetails = await _context.Stores
    .Include(s => s.Products)
    .ThenInclude(p => p.ProductAttributes)
    .ProjectTo<StoreDetails>(new MapperConfiguration(c => c.CreateProfile("TEST", e => {
        e.CreateMap<Store, StoreDetails>();
    })))
    .SingleOrDefaultAsync(p => p.Id == id);

Store对象中一切正常,但是在StoreDetails ProductAttributes中每次都为空。

为什么AutoMapper无法使用ProjectTo映射第二级导航属性?

注意:我正在使用AutoMapper 8.1.1。

1 个答案:

答案 0 :(得分:0)

我认为您应该向此类添加虚拟属性

public class Store {
    public int Id { get; set; }

    //Other properties

    [JsonIgnore]
    public virtual ICollection<Product> Products { get; set; }
}

public class StoreDetails {
    public int Id { get; set; }

    //Other properties

    public virtual ICollection<Product> Products { get; set; }
}

也可以使用“个人资料”进行映射

public class StoreProfile : Profile
{
    public StoreProfile ()
    {
        CreateMap<Store, StoreDetails>(MemberList.None).ReverseMap();
    }
}

然后在您的startup.cs中注册

services.AddAutoMapper();

这是您映射到个人资料的方式

private readonly IMapper _mapper;

var storeDetails = await _context.Stores
    .Include(s => s.Products)
    .ThenInclude(p => p.ProductAttributes)
    .Select(
      x => new ViewModel {
        SomeObject = _mapper.Map<Store, StoreDetails>(x)
      } 
    )
    .SingleOrDefaultAsync(p => p.Id == id);

以下是我正在使用的版本

<PackageReference Include="AutoMapper" Version="8.0.0" />
<PackageReference Include="AutoMapper.Extensions.Microsoft.DependencyInjection" Version="6.0.0" />