在我的ASP.NET MVC 3项目中,我在一个单独的类库项目中实现了存储库模式。
此外,我使用EF作为ORM。我还使用IValidatableObejct接口实现了一些模型验证。以下是它的样子:
[MetadataType(typeof(AccommPropertySeasonPeriodAlias.MetaData))]
public partial class AccommPropertySeasonPeriodAlias : IValidatableObject {
private class MetaData {
[StringLength(5), Required]
[Display(Name = "Period Alias Name")]
public string AccommPropertySeasonPeriodAlias1 { get; set; }
}
public IEnumerable<ValidationResult> Validate(ValidationContext validationContext) {
var repo = new AccommPropertySeasonPeriodAliasRepository();
if (repo.GetAll(this.AccommPropertySeasonID).
Where(x => x.AccommPropertySeasonPeriodAlias1 == this.AccommPropertySeasonPeriodAlias1) != null)
yield return new ValidationResult("Alias Name needs to be unique");
}
}正如您所看到的,从现在开始,我的模型完全紧密耦合,因为我直接使用了AccommPropertySeasonPeriodAliasRepository类,而不是使用IAccommPropertySeasonPeriodAliasRepository。
如何正确地进行这个操作,以便使我的模型能够,嗯,(不确定这是否是正确的词)用于单元测试的可伪造?
发布于 2011-11-10 22:21:30
验证逻辑可以使用MVC内置的解析器注入。
请参阅ModelValidatorProvider的使用情况,它是使用MVC中的注册容器解析的。
ASP.NET MVC 3: Validating model when information external to the model is required
发布于 2011-11-10 16:12:52
统一约束超出了该实体的范围。在从外部添加新实体时,应验证此约束。此验证不应属于实体本身。这取决于实体所处的上下文,而不仅仅是该实体本身。
发布于 2021-03-17 18:59:29
您可以在GetService(Type serviceType)上使用ValidationContext方法-参见:https://learn.microsoft.com/en-us/dotnet/api/system.componentmodel.dataannotations.validationcontext.getservice?view=net-5.0#System_ComponentModel_DataAnnotations_ValidationContext_GetService_System_Type_
这是一种服务定位器模式,但比使用DataAnnotationsModelValidator的一些更复杂的实现要简单得多。有时,简单解决方案(使用ServiceLocator模式)的缺点超过了复杂解决方案的成本。
https://stackoverflow.com/questions/8082451
复制相似问题