我用AutoMapper将class Foo映射到class Bar。 Bar是Foo的ViewModel。 Bar具有更少的属性,但它具有的所有属性都与相应的Foo属性完全匹配,除了Bar在Foo中不存在的其中一个属性上具有自定义验证属性。如何在使用AutoMapper时跳过自定义验证属性?
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映射一个富到酒吧,但我不希望当映射恰好是运行“CustomValidation”属性。
这是我的映射代码看起来像......
Mapper.Initialize(cfg => cfg.CreateMap<Foo, Bar>(MemberList.None)
.ForMember("Prop3", m => m.Ignore()));
即使在MemberList.None在和的Prop3被明确忽略传递...它仍是起火的CustomValidation属性。
我该如何阻止它这样做?
或可替代...
我能火与非默认构造函数的CustomValidation属性?
把这个相当奇怪的问题放在上下文中。我试图单元测试一个执行这个映射的Controller方法。 CustomValidation属性命中数据库,我想避免这种情况来加速单元测试。我确实已将CustomValidation属性设置为在构造函数中接受IoC容器,这将允许我传入模型并避开数据库,这将是完全避免验证的完美替代解决方案。
自定义验证属性已经接受IoC容器作为构造参数,以便我可以用模拟库进行单元测试。当我单独测试自定义验证属性时,这很好。 问题是,我试图单元测试一个控制器方法,它自己正在执行从模型到ViewModel的AutoMapper映射,并且ViewModel包含自定义验证属性。 我可以将IoC容器传入控制器,并分别传递到自定义属性中,但看起来并不是通过AutoMapper从控制器传递给属性。 – spoonraker
好吧我现在明白了。但是,我们清楚地知道,你正在谈论设定模型tate的价值的验证。有效,对吗?如果是的话,你怎么扼杀它?粘贴该代码将帮助我帮助你。 –
* ModelState.IsValid –