Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/csharp/257.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C# 使用AutoMapper时,如何跳过自定义验证属性?_C#_Asp.net_Unit Testing_Automapper_Custom Attributes - Fatal编程技术网

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

C# 使用AutoMapper时,如何跳过自定义验证属性?,c#,asp.net,unit-testing,automapper,custom-attributes,C#,Asp.net,Unit Testing,Automapper,Custom Attributes,我正在用AutoMapper将类Foo映射到类Bar。Bar是Foo的一个视图模型。Bar的属性较少,但它拥有的所有属性都与相应的Foo属性完全匹配,除了Bar在Foo中不存在的其中一个属性上具有自定义验证属性 public class Foo { string Prop1 { get; set; } string Prop2 { get; set; } string Prop3 { get; set; } string Prop4 { get; set; } s

我正在用AutoMapper将类Foo映射到类Bar。Bar是Foo的一个视图模型。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映射到一个条,但我不想在映射发生时运行“CustomValidation”属性

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

            Mapper.Initialize(cfg => cfg.CreateMap<Foo, Bar>(MemberList.None)
            .ForMember("Prop3", m => m.Ignore()));
Mapper.Initialize(cfg=>cfg.CreateMap(MemberList.None)
.ForMember(“Prop3”,m=>m.Ignore());
即使有MemberList.None被传入并且Prop3被特别忽略。。。它仍然激发CustomValidation属性

我怎样才能阻止它那样做

或者

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


把这个相当奇怪的问题放在上下文中。我正在尝试对执行此映射的控制器方法进行单元测试。CustomValidation属性命中数据库,我希望避免这种情况,以加快单元测试。我确实设置了CustomValidation属性来接受构造函数中的IoC容器,这将允许我传入一个模拟并避免数据库,这将是完全避免验证的完美替代解决方案。

Auto Mapper不关心validation属性

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


我真的认为自动映射器不是您的问题。

自定义验证属性已经接受IoC容器作为构造函数参数,因此我可以使用模拟存储库对其进行单元测试。当我单独对自定义验证属性进行单元测试时,这一切都很好。问题是,我正在尝试对一个控制器方法进行单元测试,该方法本身正在执行从模型到ViewModel的AutoMapper映射,并且ViewModel包含自定义验证属性。我可以将一个IoC容器分别传递到控制器和自定义属性中,但似乎不能通过AutoMapper从一个控制器传递到另一个属性。但我们要明确的是,你们所说的验证恰好是用来设置模型值的。是有效的,对吗?如果是的话,你是怎么做的?粘贴该代码将帮助我帮助您。*ModelState.IsValidExactly。“CustomValidation”属性用于为Bar类设置ModelState.IsValid。Foo类没有此属性。当AutoMapper将我的Foo映射到Bar时,它似乎正在使用自定义属性验证生成的Bar。我只想不验证结果栏,或者将IoC容器传递到CustomValidation类构造函数中。“我似乎也做不到。”斯彭瑞克,我认为AutoMapper尝试执行这些操作是没有意义的。我建议如下:在调试模式下执行测试,并在属性内设置断点。然后分析了stacktrace。这将告诉你它是AutoMapper还是其他什么。