我想创建此实体模型之间的映射:
public class ProductType
{
public int Id { get; set; }
public string Title { get; set; }
public int SortOrder { get; set; }
public ICollection<ProductIdentifierInType> Identifiers { get; set; }
public ICollection<ProductPropertyInType> Properties { get; set; }
public ICollection<Product> Products { get; set; }
}
...以及这个 View 模型:
public class ViewModelProductType
{
public int Id { get; set; }
public string Title { get; set; }
public int SortOrder { get; set; }
public IList<ViewModelProductIdentifier> Identifiers { get; set; }
public IList<ViewModelProductProperty> Properties { get; set; }
public ICollection<ViewModelProduct> Products { get; set; }
}
...但是由于 View 模型中的标识符和属性与实体模型中的类型不同,因此它无法直接工作,如下所示:
CreateMap<ProductType, ViewModelProductType>();
我不想对我的模型进行太多改变。在实体模型中,我需要Identifiers
和Properties
分别为ProductIdentifierInType
和ProductPropertyInType
,因为有很多- 存在一对多关系,这需要链接表。
但是在 View 模型中,我需要Identifiers
和Properties
作为完整的对象,以便在 View 中显示它们的属性。
有没有办法通过映射来实现这一点?也许使用 .ForPath()
来获取两个对象的属性?
最佳答案
假设您已经定义了查看模型映射的直接实体:
CreateMap<ProductIdentifier, ViewModelProductIdentifier>();
CreateMap<ProductProperty, ViewModelProductProperty>();
现在,使用 MapFrom
表达式中的 LINQ Select
提取相应的成员就足够了。需要了解的重要一点是 AutoMapper 不要求返回表达式的类型与目标类型匹配。如果它们不匹配,AutoMapper 将使用该类型的显式或隐式映射。
CreateMap<ProductType, ViewModelProductType>()
.ForMember(dst => dst.Identifiers, opt => opt.MapFrom(src =>
src.Identifiers.Select(link => link.Identifier)))
.ForMember(dst => dst.Properties, opt => opt.MapFrom(src =>
src.Properties.Select(link => link.Property)))
;
关于c# - 通过 AutoMapper 映射获取相关数据?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49587239/