在我自己的持久框架中使用数据注释和验证?
我正在构建一个依赖于旧遗留系统的程序。 我特别在 POCO/持久不可知模型类上编写自定义 CRUD 存储库。
例如(简化):
public class Company { // No dep with the legacy objects
public string CompanyName {get; set;}
}
public class CompanyRepository { // other project
public Company Get(ID companyID)
{
var myOldSchoolCompany = oldSystem.GetCompany(companyID.Key);
return new Company { CompanyName = myOldSchoolCompany.CompanyName; }
}
public Company Save(Company company)
{
var myOldSchoolCompany = oldSystem.GetCompany(companyID.Key);
myOldSchoolCompany.CompanyName = company.CompanyName;
oldSystem.Save(myOldSchoolCompany);
}
}
此代码按预期工作,但我想进一步添加检查和验证。 我需要能够具有必填字段、范围验证等。
我喜欢 DataAnnotation 机制,它允许我在模型本身上添加这些信息。 是否有可能(并且是一个好主意)重用这种机制? 准确地说,是否有一个 OOB Validate 方法可以验证模型对象?
提前致谢, 史蒂夫
I'm building a program that relies on a old legacy system.
I'm especially writing a custom CRUD repository over a POCO/persistent agnostic model classes.
Ex (simplified):
public class Company { // No dep with the legacy objects
public string CompanyName {get; set;}
}
public class CompanyRepository { // other project
public Company Get(ID companyID)
{
var myOldSchoolCompany = oldSystem.GetCompany(companyID.Key);
return new Company { CompanyName = myOldSchoolCompany.CompanyName; }
}
public Company Save(Company company)
{
var myOldSchoolCompany = oldSystem.GetCompany(companyID.Key);
myOldSchoolCompany.CompanyName = company.CompanyName;
oldSystem.Save(myOldSchoolCompany);
}
}
this code is working as expected, but I'd like to go further, with adding checks and validations.
I need to be able to have mandatory fields, range validation, etc.
I like the DataAnnotation mechanisms that allow me to add this informations on the model itself.
Is it possible (and a good idea) to reuse this mechanisms ?
Precisely, is there a OOB Validate method that can validate a model object ?
thanks in advance,
steve
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
我认为使用注释进行验证是一个很好的做法。一些常见的框架如 ASP.NET MVC、Entity Framwork 都利用了这一点。
您可以使用验证器 用于验证带注释的对象的类。
我建议您构建一个小型框架来集成注释框架和系统类。
I think it's a good practice to use annotations for validation. Some common frameworks like ASP.NET MVC, Entity Framwork make use of this.
You can use Validator class to validate an annotated object.
I recommend you build a small framework to integrate the annotation framework and your system classes.