繁体   English   中英

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

[英]How can I skip a custom validation attribute when using AutoMapper?

我使用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容器,这将允许我传递模拟信息并避免使用数据库,这将是完全避免验证的完美解决方案。

Auto Mapper不在乎验证属性。

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

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM