c# - 通过 AutoMapper 映射获取相关数据?

标签 c# asp.net-core-mvc automapper entity-framework-core

我想创建此实体模型之间的映射:

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>();

我不想对我的模型进行太多改变。在实体模型中,我需要IdentifiersProperties分别为ProductIdentifierInTypeProductPropertyInType,因为有很多- 存在一对多关系,这需要链接表。

但是在 View 模型中,我需要IdentifiersProperties作为完整的对象,以便在 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/

相关文章:

asp.net-mvc - automapper,您将代码放在哪里以将 View 模型映射到实体

c# - 是否可以在 MSSQL 过程本身中格式化日期,以便它可以显示为非正式日期?

html - asp.net core波浪号斜杠(~/)不解析图像路径

c# - 如何读取 ASP.NET Core Response.Body?

c# - Automapper:如何不重复从复杂类型到基类的映射配置

c# - 具有 IHttpActionResult 返回类型和映射数据的方法的 Asp.net 单元测试

c# - 在 IDisposable 对象数组中使用 Dispose() 或不使用 Dispose() 元素?

c# - 使用 Array.Sort() 进行浮点排序

c# - 内存不足异常前的位图最大尺寸

c# - Azure Web 应用程序服务使用混合连接管理器使用 HttpClient 调用本地 WEB API