c# - 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++ - 这是未定义的,因为我 memcpy'ed 一个 non_trivially_copyable 类型?
- aws-organizations - 使用 AWS CLI 描述组织并创建 OU
- java - 如何遍历行的迭代器
- matlab - U Net 纹理分割(验证数据集)
- javascript - 如何初始化 i18next
- reactjs - 当我添加 useFirestoreForProfile 和 userProfile 时,我的“用户”集合没有出现在我的控制台中
- c - 我正在尝试找到一种方法让我的服务器套接字打开,直到连接的客户端发送他想要的所有消息
- python - 处理多个用户发送命令
- python - 您如何获得 statsModels 中测试数据的调整后 R 平方?
- java - 如何修复此 Firebase RunTime DB 错误,其中创建了数据库条目和身份验证详细信息,但所有字段均为空?