[英]Dot Net Database driven Data annotation
I have numbers of model in .net core web API and I save all model properties in database now when post request to action method then it should validate those property on the base of database store annotation. I have numbers of model in .net core web API and I save all model properties in database now when post request to action method then it should validate those property on the base of database store annotation.
And I didn't want to write hard coded annotation on each and every property.而且我不想在每个属性上都写硬编码注释。 There should be generic class or method that add different data annotation after load from the database at run time and validate model on base of database properties.应该有通用的 class 或方法,在运行时从数据库加载后添加不同的数据注释,并根据数据库属性验证 model。 Is there any way to resolve it.有什么办法可以解决。
Remember: I did't use like this:记住:我没有这样使用:
public class UserAddress
{
[Required] // this is data annotation and I didn't want to use like this
public string CityCode { get; set; }
}
There are lot of examples to create custom validate class and use Data Annotation on model properties... but I did not want to use hard coded data annotation but it should be add at run time from database有很多示例可以创建自定义验证 class 并在 model 属性上使用数据注释......但我不想使用硬编码数据注释,但它应该在运行时从数据库中添加
Instead of that I want to use like this:而不是我想这样使用:
public class UserAddress
{
// this is without data annotation. I want my model should like this
public string CityCode { get; set; }
}
There should be generic code that validate class properties after compare with the database properties and validate on the base of database values.应该有通用代码在与数据库属性比较后验证 class 属性并根据数据库值进行验证。
Consider using FluentValidation
.考虑使用FluentValidation
。 With this you could write Validator
classes for your models like this:有了这个,你可以为你的模型编写Validator
类,如下所示:
public class UserAddressValidator : AbstractValidator<UserAddress> {
public UserAddressValidator() {
RuleFor(x => x.CityCode ).NotNull();
}
}
You could read more at official docs: https://docs.fluentvalidation.net/en/latest/index.html您可以在官方文档中阅读更多内容: https://docs.fluentvalidation.net/en/latest/index.html
EDIT编辑
There is an example on how to move rules to XML: http://www.primaryobjects.com/2012/05/16/loading-c-mvc-net-data-annotation-attributes-from-xml-form-validation/有一个关于如何将规则移动到 XML 的示例: http://www.primaryobjects.com/2012/05/16/loading-c-mvc-net-data-annotation-attributes-from-xml-form-validation/
You could implement something like this to get validation rules from db, still, i think that strongly-typed declarations from initial answer are better你可以实现这样的东西来从数据库中获取验证规则,不过,我认为来自初始答案的强类型声明更好
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.