如何告诉Automapper检查是否所有源属性都有目标属性

本文关键字:属性 目标 何告诉 Automapper 检查 是否 | 更新日期: 2023-09-27 18:12:56

我们有两个类:

public class Foo
{
    public int A { get; set; }
    public int B { get; set; }
    public int C { get; set; }
}
public class Bar
{
    public int A { get; set; }
    public int B { get; set; }
} 

和映射配置

 Mapper.CreateMap<Foo, Bar>;

是否有可能Automapper自动检查所有源属性是否有相应的目标属性,在我的例子中抛出一个异常,通知我们Foo.C属性没有映射到任何东西。Mapper.AssertConfigurationIsValid()只检查另一种方式-所有目标属性都有源属性,所以它对我的情况没有帮助。

如何告诉Automapper检查是否所有源属性都有目标属性

也许您可以使用一个hack并在另一个方向上测试映射。比如:

Mapper.CreateMap<Bar, Foo>; // Swap the direction of the mapping
Mapper.AssertConfigurationIsValid()

我知道这不是最理想的,但这可能是一个快速的解决方案。