我尝试使用AutoMapper将三个实体模型映射到一个视图模型中。最终输出应该是递归类别树,其中包含类别中的产品。类别树正在运行,但viewmodel的Products
- 属性为null
。我的查询是返回类别和产品,因此我认为映射不知道如何将产品映射到视图模型。
我的实体模型:
public class ProductCategory
{
public int Id { get; set; }
public int SortOrder { get; set; }
public string Title { get; set; }
[ForeignKey(nameof(ParentCategory))]
public int? ParentId { get; set; }
// Nav.props:
public ProductCategory ParentCategory { get; set; }
public ICollection<ProductCategory> Children { get; set; }
public List<ProductInCategory> ProductInCategory { get; set; }
}
public class ProductInCategory
{
public int Id { get; set; }
public int ProductId { get; set; }
public int SortOrder { get; set; }
public int ProductCategoryId { get; set; }
public bool IsProductCategoryFrontPage { get; set; }
// Nav.props.
public Product Product { get; set; }
public ProductCategory ProductCategory { get; set; }
}
public class Product
{
public int Id { get; set; }
public string Title { get; set; }
public string Info { get; set; }
public decimal Price { get; set; }
// Nav.prop:
public List<ProductInCategory> InCategories { get; set; }
}
我的观点模型:
public class ViewModelProductCategory
{
public int Id { get; set; }
public int? ParentId { get; set; }
public string Title { get; set; }
public int SortOrder { get; set; }
public string ProductCountInfo
{
get
{
return Products != null && Products.Any() ? Products.Count().ToString() : "0";
}
}
public ViewModelProductCategory ParentCategory { get; set; }
public IEnumerable<ViewModelProductCategory> Children { get; set; }
public IEnumerable<ViewModelProduct> Products { get; set; }
}
我尝试了这种映射(映射类别,但没有产品):
CreateMap<ProductCategory, ViewModelProductCategory>();
CreateMap<ViewModelProductCategory, ProductCategory>();
我尝试了这种映射(映射类别,但没有产品):
CreateMap<ProductCategory, ViewModelProductCategory>()
.ForMember(dto => dto.Id, opt => opt.MapFrom(src => src.Id))
.ForMember(dto => dto.ParentId, opt => opt.MapFrom(src => src.ParentId))
.ForMember(dto => dto.Title, opt => opt.MapFrom(src => src.Title))
.ForMember(dto => dto.SortOrder, opt => opt.MapFrom(src => src.SortOrder))
.ForMember(dto => dto.Children, opt => opt.MapFrom(src => src.Children))
.ForMember(dto => dto.Products, opt => opt.MapFrom(src => src.ProductInCategory));
答案 0 :(得分:3)
您希望跳过视图模型中的联结(链接)实体。
为此,首先创建从Product
到ViewModelProduct
的映射,然后使用投影转换ProductCategory.ProductInCategory
定义ViewModelProductCategory.Products
到List<ProductInCategory>
的映射。 {1}}。 AutoMapper会谨慎地将IEnumerable<Product>
转换为IEnumerable<Product>
,就像查询List<ViewModelProduct>
时一样:
Products