首页 > 解决方案 > AutoMapper 忽略动态或非完全限定映射配置上的非派生属性

问题描述

我的 .NET CORE 2.1 代码和 AutoMapper 用于将 DTO 映射到 DomainModels 时遇到问题,反之亦然。

最初我使用 CreateRequest DTO 来创建数据,该数据映射到我的域模型。出于更新原因,我使用派生自我的 CreateRequest DTO 的 UpdateRequest DTO。我的 UpdateRequest 类上还有一些属性,它们也存在于我的完整域模型类中。

现在,在创建请求创建模型实体后,我能够在读取模型实体时重现一个奇怪的错误。使用 AutoMapper 使用我的 UpdateRequest DTO 更新此读取模型会引发以下问题:名为“VersionNumber”的属性似乎被忽略,而其他属性已成功设置。看起来 AutoMapper 将继承的类 CreateRequest 保存为唯一的现有映射,并使用它来映射派生类 UpdateRequest。

我在 LinqPad 中重新创建了这种情况并在此处添加使用的代码。

static bool init = false;
void Main()
{
    init.Dump("IsInitialized"); 
    if (!init) 
    {
        // Configuration 1
        AutoMapper.Mapper.Initialize(cfg => { cfg.CreateMissingTypeMaps = true; cfg.ValidateInlineMaps = false; }); 

        // Configuration 2
//      AutoMapper.Mapper.Initialize(cfg => 
//      { 
//       cfg.CreateMap<Bar, Model>();
//       // Configuration 2, also define map for the derived type
////         cfg.CreateMap<Foo, Model>();
//      });

        init = true;
    }

    // Create model and save db changes
    Model created = AutoMapper.Mapper.Map<Model>(new Bar { Name="Bar" });
    created.Dump("Created");

    // Read model from db
    var b = new Model { Name = created.Name, VersionNumber = created.VersionNumber };

    // Create derived model to update read model
    var f = new Foo { Name = "Foo", VersionNumber = 123 };

    // Update entity
    var result = AutoMapper.Mapper.Map(f, b);
    b.Dump("Updated Bar");
    result.Dump("Result = Updated Bar");    
}

class Foo : Bar {
public long? VersionNumber {get; set;}
}

class Model {
public string Name {get; set;}
public long VersionNumber {get; set;}
}

class Bar {
public string Name {get;set;}
}

此外,我必须解释我使用的配置。配置 1 是我第一次尝试仅使用“动态”地图配置。测试此错误时使用了配置 2。最后,仅当您定义了两种类型,即基本类型和派生类型时,映射才会起作用。

1 的结果应该是“VersionNumber”123,而不是 0。2 相同,但没有正确定义。只有在两个映射中使用 2 才会产生预期的结果。所有三个配置选项都适用于“名称”属性。

在 LinqPad 中,我引用了 AutoMapper 的以下版本: ....nuget\packages\automapper\7.0.1\lib\netstandard2.0

我希望在动态配置的初始映射期间发生错误,或者 AutoMapper 识别出我想要映射派生类型,因此必须使用不同的映射。

标签: c#.net-coreautomapper-7

解决方案


推荐阅读