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

问题描述 投票:0回答:1

如果我调用 AutoMapper 的

AssertConfigurationIsValid()
函数,它应该为映射类的每个属性抛出异常,该类使用未映射的类型。如果至少有一个属性属于
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)
时,并且只有当我的源对象在
null
属性中实际上具有非
SecondLevel
值时,我才会得到异常。

如果我注释掉

ObjectProperty
属性,则对
AssertConfigurationIsValid()
的调用会引发预期的异常。

这导致了一个问题,我发现映射丢失已经太晚了,因为在测试期间该值始终为

null

除了去掉

object
属性之外,还有办法避免这个问题吗?

c# automapper .net-6.0
1个回答
0
投票

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

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

© www.soinside.com 2019 - 2024. All rights reserved.