处理数据验证的正确方法
我的应用程序中有一个员工类别。该类的构造函数采用员工 ID。我尝试检查员工 ID 是否有效的方法是这样的
Employee emp = new Employee("E11234");
if (emp.IsValid())
{
// do whatever is required
}
else
{
// show an error message
}
在构造函数中,我尝试访问数据库,如果我可以检索记录,我会填充私有成员的值,否则如果不存在记录,我会设置isValid 属性设置为 false。
这是实现我想要的目标的正确方法还是有更好的方法?
I have an employee class in my application. The constructor for the class takes an employee ID. The way I try to check if the employee ID is valid is something like this
Employee emp = new Employee("E11234");
if (emp.IsValid())
{
// do whatever is required
}
else
{
// show an error message
}
In the constructor, I try to access the database and if I can retrieve records, I fill the values for the private members, else if no records exist, I set the isValid property to false.
Is this a correct way of achieving what I want to or is there a better method?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
您应该将数据库访问与实体类(Employee)分开。分离的一种选择是使用 Repository-pattern 来加载和保存员工。存储库负责访问您的数据库,员工不必担心它来自哪里或将存储在哪里。
有很多关于使用存储库的好教程,在 Stackoverflow 中我们有一个很好的问题关于这个话题。使用存储库时,您的代码看起来更像是这样:
关于验证,您的员工类也不应该访问该存储库中的数据库。您可以使用 Validate 方法创建 EmployeeValidator 类,然后该类执行所有必需的验证。
我最好的建议是,您应该尝试让您的实体远离您的基础设施。
You should separate the database access from your entity class (Employee). One option for separation is to use Repository-pattern for loading and saving the employee. The repository is responsible for accessing your database and the employee doesn't have to worry about where it came from or where you're going to store it.
There's many good tutorials available on using a repository and here in Stackoverflow we have a good question about this topic. When using a repository, your code would look like more like this:
About the validation, your employee-class should not hit the the database in that one either. You could create a EmployeeValidator-class with a Validate-method, which then does all the required validation.
My best advice is that you should try to keep your entities away from your infrastructure.