c# - 如果对象属性存在,为什么 AutoMapper 验证不起作用?

标签 c# automapper .net-6.0

如果我调用AssertConfigurationIsValid() AutoMapper 的函数应该为映射类的每个属性(使用未映射的类型)抛出异常。如果至少有一个属性的类型为 object,则似乎不会发生这种情况.

我知道 AutoMapper 无法检查是否可以分配给 object 的所有内容。属性已映射,但我认为它仍然会对使用未映射类型的其他属性引发异常。

如果我有这些简单的类:

public class RootLevel
{
    public object ObjectProperty { get; set; }
    public SecondLevel SecondLevel { get; set; }
}

public class RootLevelDto
{
    public object ObjectProperty { get; set; }
    public SecondLevelDto SecondLevel { get; set; }
}

public class SecondLevel
{
}

public class SecondLevelDto
{
}

我(错误地)只映射了 RootLevel类并尝试执行此代码:

var config = new MapperConfiguration(config =>
{
    config.CreateMap<RootLevel, RootLevelDto>();
});
config.AssertConfigurationIsValid();
var mapper = new Mapper(config);

var source = new RootLevel
{
    SecondLevel = new SecondLevel()
};
var mapped = mapper.Map<RootLevelDto>(source);

我希望调用 config.AssertConfigurationIsValid()抛出异常,因为类型 SecondLevel未映射。但我只有在调用 mapper.Map<RootLevelDto>(source) 时才会得到异常,并且仅当我的源对象实际上具有非 nullSecondLevel 中的值属性。

如果我注释掉ObjectProperty属性,调用 AssertConfigurationIsValid()抛出预期的异常。

这导致了一个问题,我发现缺少映射为时已晚,因为该值始终为 null测试期间。

除了摆脱 object 之外,还有其他方法可以避免此问题吗?属性?

最佳答案

这是一个错误,现已解决。尝试MyGet构建。

一个脆弱的解决方法是在类定义的末尾声明对象属性。

关于c# - 如果对象属性存在,为什么 AutoMapper 验证不起作用?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/76836020/

相关文章:

c# - 从 C# 调用 C++ 函数,具有大量复杂的输入和输出参数

asp.net-core-3.1 - Microsoft.NET.Sdk.Razor.StaticWebAssets.targets(442,5) : error : Two assets found targeting the same path with incompatible asset kinds

c# - MS-Access 查询语法

c# - DataItem=null on binding,找不到原因?

c# - 初始化后将配置文件添加到自动映射器

c# - 为什么 AutoMapper 不使用 ProjectTo 映射二级导航属性?

.net - HangFire 作为 .NET 6 的 Windows 服务

azure - .net 6.0 与 nuget 包的兼容性问题

c# - 在 C# 中,我正在调用一个公共(public) API,它的 API 限制为每秒 10 次调用

c# - 使用 Automapper 映射对象列表