使用AutoMapper时如何跳过自定义验证属性?

时间:2016-08-11 18:36:23

标签: c# asp.net unit-testing automapper custom-attributes

我使用AutoMapper将类Foo映射到类Bar。 Bar是Foo的ViewModel。 Bar具有较少的属性,但它具有的所有属性都与相应的Foo属性完全匹配,除了Bar在其中一个不存在于Foo中的属性上具有自定义验证属性。

public class Foo 
{
   string Prop1 { get; set; }
   string Prop2 { get; set; }
   string Prop3 { get; set; }
   string Prop4 { get; set; }
   string Prop5 { get; set; }
}

public class Bar
{
   string Prop1 { get; set; }
   string Prop2 { get; set; }

   [CustomValidation]       
   string Prop3 { get; set; }
}

我想使用AutoMapper将Foo映射到Bar,但我想要" CustomValidation"映射发生时要运行的属性。

这是我的映射代码的样子......

            Mapper.Initialize(cfg => cfg.CreateMap<Foo, Bar>(MemberList.None)
            .ForMember("Prop3", m => m.Ignore()));

即使在中传递了MemberList.None,Prop3也会被特别忽略......它仍会触发CustomValidation属性。

如何阻止它这样做?

或者......

我可以使用非默认构造函数触发CustomValidation属性吗?

把这个相当奇怪的问题放在上下文中。我试图对执行此映射的Controller方法进行单元测试。 CustomValidation属性命中数据库,我想避免这种情况加速单元测试。我确实将CustomValidation属性设置为接受构造函数中的IoC容器,这样我就可以传入模拟并避免使用数据库,这将是完全避免验证的完美替代解决方案。

1 个答案:

答案 0 :(得分:0)

Auto Mapper不关心验证属性。

如果您不希望在测试中执行真正的验证,我认为将数据库中的服务或存储库抽象化以便您可以在测试中模拟或存根它是一种有效的方法。

我真的认为Auto Mapper不是你的问题。

相关问题