如何在具有简单属性的实体模型和具有List <said properties =“”>的viewmodel之间进行映射?

时间:2018-03-12 08:51:45

标签: c# automapper

如何映射List<this entity model>

public class ProductCategory
{
    public int Id { get; set; }
    public string Title { get; set; }
    public int SortOrder { get; set; }
    public int? ParentId { get; set; }
}

...和此viewmodel(实体类属性Title不应映射到viewmodel属性Title,而应映射到Categories.Title):

public class ViewModelProductCategories
{
    public List<ViewModelProductCategory> Categories { get; set; }
    public string Title { get; set; }// Used to create new category the Index view
    // User Interface parameter switches:
    public bool CanCreateCategory { get; set; }
    public bool CanCreateProduct { get; set; }
}

这是ViewModelProductCategories引用的视图模型。重要的是,当我映射时,我也会获得导航属性:

public class ViewModelProductCategory
{
    public int Id { get; set; }
    public int? ParentId { get; set; }
    public string Title { get; set; }
    public int SortOrder { get; set; }
    // Nav.props:
    public List<ViewModelFrontPageProduct> FrontPageProducts { get; set; }
    public ViewModelProductCategory ParentCategory { get; set; }
    public ViewModelProductCategories Children { get; set; }
    public List<ViewModelProduct> Products { get; set; }
}

这是我的旧映射,它直接映射到ViewModelProductCategory

CreateMap<ProductCategory, ViewModelProductCategory>()
            .ForMember(dst => dst.Products, opt => opt.MapFrom(
                src => src.ProductInCategory.Select(pc => pc.Product)));

我可以通过Products在每个类别中访问ProductInCategory。我仍然需要,但类别现在将在List

2 个答案:

答案 0 :(得分:2)

如果您正确地发现问题,您希望将单个ProductCategory传递给Automapper,并在ViewModelProductCategories集合中使用一个条目获得Categories

1)定义映射ProductCategory - &gt; ViewModelProductCategory

CreateMap<ProductCategory, ViewModelProductCategory>();

2)使用此映射解析ViewModelProductCategories

中的集合
CreateMap<ProductCategory, ViewModelProductCategories>()
    .ForMember(vm => vm.Categories, 
               o => o.ResolveUsing(src => Mapper.Map<List<ViewModelProductCategory>>(src))
    );

这假设映射ProductCategory - &gt;为静态Automapper实例配置了ViewModelProductCategory。请注意,如果Automapper知道如何映射元素,它将自动创建集合。

用法:

var cat = new ProductCategory();
ViewModelProductCategories vm = Mapper.Map<ViewModelProductCategories>(cat);

答案 1 :(得分:1)

您可以使用AutoMapper,也可以Project / Select加入ViewModals

var productCategories = context.Where(<my filter>)
               .OrderBy(x => x.SortOrder)
               .Select(x => new ViewModelProductCategory()
                 {
                    Id = x.Id,
                    Title = x.Title,
                    SortOrder = x.SortOrder, 
                    ParentId = x.ParentId
                 }); 

var viewModelProductCategories  = new ViewModelProductCategories()
                {
                   Categories  = productCategories 
                   ...
                   // other shenanigans here  
                };