AutoMapper - 根据条件映射到派生对象

2024-03-01

我想根据某些属性的值将源类映射到派生(从抽象)目标类。

我有以下源类:

public partial class ApplicationDriver
{
    public virtual ICollection<ApplicationDriverEquipment> Equipments { get; set; }

}

public partial class ApplicationDriverEquipment
{
    public int Id { get; set; }
    [StringLength(256)]
    public string Make { get; set; }
    [StringLength(256)]
    public string Model { get; set; }
    [StringLength(256)]
    public string Year { get; set; }
    [StringLength(256)]
    public string VINNumber { get; set; }
    [StringLength(256)]
    public string PlateNumber { get; set; }
    [StringLength(256)]
    public string CurrentMileage { get; set; }
    [StringLength(256)]
    public string Length { get; set; }
    public string Type { get; set; }

    public int DriverId { get; set; }
    public virtual ApplicationDriver Driver { get; set; }
}

我想映射到以下类,具体取决于类型参数:

public class ApplicationDriverDomain
{
    public List<ApplicationDriverEquipmentAbstractDomain> Equipments { get; set; }

}

public abstract class ApplicationDriverEquipmentAbstractDomain
{
    public int Id { get; set; }
    public string Make { get; set; }
    public string Model { get; set; }
    public string Year { get; set; }
    public string PlateNumber { get; set; }
    public string CurrentMileage { get; set; }
    public string Type { get; protected set; }
}

public class ApplicationDriverEquipmentTractorDomain : ApplicationDriverEquipmentAbstractDomain
{
    public ApplicationDriverEquipmentTractorDomain()
    {
        Type = ApplicationDriverEquipmentTypeStaticStringsDomain.Tractor;
    }
    public string VINNumber { get; set; }
}

public class ApplicationDriverEquipmentTrailerDomain : ApplicationDriverEquipmentAbstractDomain
{
    public ApplicationDriverEquipmentTrailerDomain()
    {
        Type = ApplicationDriverEquipmentTypeStaticStringsDomain.Trailer;
    }

    public string Length { get; set; }
}

public class ApplicationDriverEquipmentStraightTruckDomain : ApplicationDriverEquipmentAbstractDomain
{
    public ApplicationDriverEquipmentStraightTruckDomain()
    {
        Type = ApplicationDriverEquipmentTypeStaticStringsDomain.StraightTruck;
    }

    public string VINNumber { get; set; }
    public string Length { get; set; }
}

public class ApplicationDriverEquipmentCargoVanDomain : ApplicationDriverEquipmentAbstractDomain
{
    public ApplicationDriverEquipmentCargoVanDomain()
    {
        Type = ApplicationDriverEquipmentTypeStaticStringsDomain.CargoVan;
    }

    public string VINNumber { get; set; }
    public string Length { get; set; }
}

我尝试这样做:

    ApplicationDriverEquipmentAbstractDomain GetEquipment(Infrastructure.Asset.ApplicationDriverEquipment infrastructure)
    {
        ApplicationDriverEquipmentAbstractDomain result = null;
        var config = new MapperConfiguration(cfg => cfg.AddProfile<AutoMapperApplicationModel>());
        var mapper = config.CreateMapper();

        switch (infrastructure.Type)
        {
            case ApplicationDriverEquipmentTypeStaticStringsDomain.Tractor:
                result = mapper.Map<ApplicationDriverEquipmentTractorDomain>(infrastructure);
                break;

            case ApplicationDriverEquipmentTypeStaticStringsDomain.Trailer:
                result = mapper.Map<ApplicationDriverEquipmentTrailerDomain>(infrastructure);
                break;

            case ApplicationDriverEquipmentTypeStaticStringsDomain.StraightTruck:
                result = mapper.Map<ApplicationDriverEquipmentStraightTruckDomain>(infrastructure);
                break;

            case ApplicationDriverEquipmentTypeStaticStringsDomain.CargoVan:
                result = mapper.Map<ApplicationDriverEquipmentCargoVanDomain>(infrastructure);
                break;

        }

        return result;
    }

        CreateMap<Infrastructure.Asset.ApplicationDriverEquipment, ApplicationDriverEquipmentTractorDomain>();
        CreateMap<Infrastructure.Asset.ApplicationDriverEquipment, ApplicationDriverEquipmentTrailerDomain>();
        CreateMap<Infrastructure.Asset.ApplicationDriverEquipment, ApplicationDriverEquipmentStraightTruckDomain>();
        CreateMap<Infrastructure.Asset.ApplicationDriverEquipment, ApplicationDriverEquipmentCargoVanDomain>();

        CreateMap<Infrastructure.Asset.ApplicationDriverEquipment, ApplicationDriverEquipmentAbstractDomain>()
            .Include<Infrastructure.Asset.ApplicationDriverEquipment, ApplicationDriverEquipmentTractorDomain>()
            .Include<Infrastructure.Asset.ApplicationDriverEquipment, ApplicationDriverEquipmentTrailerDomain>()
            .Include<Infrastructure.Asset.ApplicationDriverEquipment, ApplicationDriverEquipmentStraightTruckDomain>()
            .Include<Infrastructure.Asset.ApplicationDriverEquipment, ApplicationDriverEquipmentCargoVanDomain>()
            .ForMember(dest => dest.Type, opt => opt.ResolveUsing(GetEquipment))
            ;

        CreateMap<Infrastructure.Asset.ApplicationDriver, ApplicationDriverDomain>()
            .ForMember(dest => dest.Equipments, opt => opt.MapFrom(src => src.Equipments));

但我得到一个错误:

“映射类型错误。\r\n\r\n映射类型:\r\nApplicationDriver -> ApplicationDriverDomain\r\nInfrastruct.Asset.ApplicationDriver -> Domain.POCO.Application.ApplicationDriverDomain\r\n\r\n类型映射 配置:\r\n应用程序驱动程序 -> ApplicationDriverDomain\r\nInfrastruct.Asset.ApplicationDriver -> Domain.POCO.Application.ApplicationDriverDomain\r\n\r\n属性:\r\n设备”


Updated:

所以我相信我理解你想要做什么,很抱歉我可能稍微引导你走上了错误的道路。您的流程基本上是区分源对象是什么基础设施类型,然后创建该类型的对象。您还需要了解两种不同的 Mapper 设置方式。

在代码的第一部分中,您尝试使用 Mapper 的实例进行设置,然后使用我的使用 Mapper.Map 的静态样式,我建议始终使用静态样式,以便您能够执行更多操作引入映射配置文件的动态方法。

Mapper.Initialize(cfg => cfg.AddProfile<AutomapperRules>());
var domain = Mapper.Map<Domain.ApplicationDriverEquipmentTractorDomain>(inf);

接下来,您只需引用从基础源到配置文件中的域类型的映射类型,即

CreateMap<ApplicationDriverEquipmentInfrastructure, ApplicationDriverEquipmentTractorDomain>();
CreateMap<ApplicationDriverEquipmentInfrastructure, ApplicationDriverEquipmentTrailerDomain>();
CreateMap<ApplicationDriverEquipmentInfrastructure, ApplicationDriverEquipmentStraightTruckDomain>();
CreateMap<ApplicationDriverEquipmentInfrastructure, ApplicationDriverEquipmentCargoVanDomain>();

然后你需要做的就是打电话给你的GetEquipment描述 ApplicationDriver 的映射中的方法,即

CreateMap<ApplicationDriver, ApplicationDriverDomain>()
            .ForMember(dest => dest.Equipments, opt => opt.ResolveUsing(x => x.Equipments.Select(GetEquipment)));

private ApplicationDriverEquipmentAbstractDomain GetEquipment(ApplicationDriverEquipmentInfrastructure infrastructure)
    {
        switch (infrastructure.Type)
        {
            case "Tractor":
                return Mapper.Map<ApplicationDriverEquipmentTractorDomain>(infrastructure);
            case "Trailer":
                return Mapper.Map<ApplicationDriverEquipmentTrailerDomain>(infrastructure);
            case "StraightTruck":
                return Mapper.Map<ApplicationDriverEquipmentStraightTruckDomain>(infrastructure);
            case "CargoVan":
                return Mapper.Map<ApplicationDriverEquipmentCargoVanDomain>(infrastructure);
        }
        return null;
    }

用法示例:

Mapper.Initialize(cfg => cfg.AddProfile<AutomapperRules>());

var inf = new ApplicationDriverEquipmentInfrastructure()
{
     CurrentMileage = "mil",
     Length = "123",
     Make = "ccc",
     Model = "15",
     Type = "Tractor",
     VINNumber = "vin"
};

var driver = new ApplicationDriver()
{
     Equipments = new List<ApplicationDriverEquipmentInfrastructure>() {inf}
};

var domain = Mapper.Map<ApplicationDriverDomain>(driver);
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

AutoMapper - 根据条件映射到派生对象 的相关文章

随机推荐

  • 具有多个键和关联值的可编码枚举

    我已经看到了有关当所有情况都有关联值时如何使枚举符合 Codable 的答案 但我不清楚如何混合具有和不具有关联值的情况的枚举 如何针对给定情况使用同一密钥的多个变体 如何对没有关联值的情况进行编码 解码 enum EmployeeClas
  • 使用属性调用方法

    我有各种单独的方法 它们都需要执行相同的功能 然后才能继续自己的实现 现在我可以在每个方法中实现这些功能 但我想知道是否有一种方法可以利用attributes去做这个 作为一个非常简单的示例 所有网络调用都必须检查网络连接 public v
  • 即使我清除缓存,.gitignore 也不起作用

    在将初始提交推送到 git 存储库后 我犯了创建 gitignore 文件的错误 我的 gitignore 非常简单 它只包含 node modules 我尝试过以下方法 git rm cached rf git add git commi
  • 如何将按“Enter”键与单击按钮关联起来?

    在我的 swing 程序中 我有一个 JTextField 和一个 JButton 我希望 一旦用户按下 enter 键 JButton 的 actionListener 就会运行 我该怎么做 提前致谢 JRootPane 有一个方法 se
  • Python - 列表字典

    制作列表字典的最佳方法是什么 例如 如果我有列表列表1 列表2并想做一本字典my dict像那样 my dict list1 list1 list2 list2 我发现了this https stackoverflow com questi
  • docker-compose up 不重新创建容器

    我创建了两个容器 一个是 oracle db 一个是 apache tomcat 我使用以下 docker compose 运行它们 version 3 4 services tomcat build tomcat ports 8888 8
  • 运行 StarTeam 2008 Release 2 客户端时出现“无法创建 Java 虚拟机”错误

    为什么 StarTeam 2008 Release 2 Client 没有在我的计算机上正确安装 每当我尝试启动它时 都会收到 无法创建 Java 虚拟机 错误 正如我之前所想 这不是定位 Java 虚拟机的问题 而是内存分配问题 在 St
  • Facebook 聊天机器人 - 如何测试欢迎消息?

    我的聊天机器人运行良好 但我在调试欢迎消息功能时遇到了麻烦 因为它仅在发起对话时显示 尽管我很确定在同事手机上尝试过它不起作用 如何重置我的聊天 以便将我视为与之交互的新用户 这是我目前受欢迎的 PHP 脚本
  • 如果使用 Android 后台服务,Flutter 会停留在“等待观测站端口可用”

    我一直在尝试为 Flutter 编写平台代码来启动后台服务 在这里 我使用了一个最小的例子 没有actual所做的工作表明该应用程序根本无法运行 实际的flutter代码根本没有修改 MainActivity java public cla
  • AnyLogic 计算机处理器需要建议 - 单核速度与核心数量?

    我在一台老式电脑上进行建模 最近获得了一些实验室资金来购买一台新的建模计算机 处理器的选择让我感到困惑 为了获得最佳的 AnyLogic 仿真建模 我应该专注于最大化单核速度还是最大化处理器核心数量 另外 高端显卡有帮助吗 我从我的工程同事
  • 如何使用 Java 或 CMD 获取 PC 硬件信息

    我正在创建一个 Java 桌面应用程序 用于报告 Windows 计算机 XP Vista 和 W7 的性能和统计信息 使用 Java 或命令行如何获取以下信息 制造商 戴尔 惠普 模数 处理器类型 处理器尺寸 系统类型 储存空间 内存总计
  • Android - 使滑动抽屉从左向右滑动

    我已经使用下面的 XML 布局在我的应用程序中实现了 滑动抽屉 我从 androidpeople com 得到这个例子
  • 使用 C# 识别 CPU 架构类型

    我想检查用户运行的是哪个CPU架构 是吗 i386 或 X64 或 AMD64 我想用 C 来做 我知道我可以尝试 WMI 或注册表 除了这两种还有其他办法吗 我的项目目标是 NET 2 0 让我来到这里的是检查 32 位与 64 位操作系
  • Python/Firefox 无头抓取脚本中的“无法解码来自木偶的响应”消息

    美好的一天 我在这里和谷歌上进行了大量搜索 但尚未找到解决此问题的解决方案 场景是 我有一个 Python 脚本 2 7 它循环访问多个 URL 例如 想想亚马逊页面 抓取评论 每个页面都有相同的 HTML 布局 只是抓取不同的信息 我将
  • 如何在 webdriverio 中结束浏览器会话来关闭浏览器?

    我有以下测试用例 在wdio conf js afterTest async function test context error result duration passed retries await browser end Erro
  • 如何通过名称调用私有函数

    如何通过名称调用函数 实际上我知道如何按名称调用函数 但我找不到所需的范围 所以现在我必须使用this get 小部件名称 它适用于 get publishedBuildsWidget1但我想让函数成为私有函数 所以我想按名称调用 get
  • 使用 jQuery 和 Ajax 提交 Rails 表单

    编辑 想通了所以问一个相关的问题 这是我的 JavaScript jQuery ajaxSetup beforeSend function xhr xhr setRequestHeader Accept text javascript jQ
  • 更改子类的超类实例变量的值

    我发现我可以在子类中这样做 ParentClass variable value 但有人告诉我 最好使用 get set 方法 而不是直接访问类外部的变量 尽管这是当我在另一个类中有该类的实例时 而不是子类和超类 那么是否有更好的方法来做到
  • 如何通过存储过程获取数据表

    以下是我的存储过程 ALTER PROCEDURE SP GetModels CategoryID bigint AS BEGIN Select ModelID ModelName From Model where CategoryID C
  • AutoMapper - 根据条件映射到派生对象

    我想根据某些属性的值将源类映射到派生 从抽象 目标类 我有以下源类 public partial class ApplicationDriver public virtual ICollection