如何在不保存的情况下验证ASP.NET MVC实体框架中的数据 [英] How do I Validate data in ASP.NET MVC Entity Framework without saving it

查看:53
本文介绍了如何在不保存的情况下验证ASP.NET MVC实体框架中的数据的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在建立一个网站,允许俱乐部将其会员名单上传为CSV文件。



我已设置了四个步骤(四个单独的网站页面):

1.上传文件

2.读取列标题并映射到数据库字段

3.阅读整个CSV文件根据数据库要求检查每个字段

4.如果没有重大错误,请将所有数据加载到数据库中。



步骤3,我生成详细报告(例如xyz不是有效的电子邮件地址)。为此,我真的想利用与模型中每个字段相关联的数据注释,但我无法弄清楚如何访问它们。



目前,我已经使用从模型中手动转录的信息设置了字段级检查,但这非常不令人满意,因为更改模型中的StringLength设置意味着要记住单独更新验证例程。



我已经搜索了我能想到的搜索词的每个组合,试图找到如何在不使用SaveChanges()的情况下验证数据功能,但无济于事。



当然,我不能成为世界上唯一想做这样事的人吗?

I am setting up a website which will allow clubs to upload their membership lists as CSV files.

I have set up a four step process (four separate web pages):
1. Upload the file
2. Read column headings and map to database fields
3. Read the whole CSV file and check every field against the database requirements
4. If there are no major errors, load all the data into the database.

In step 3, I produce a detailed report (e.g. "xyz" is not a valid email address). To do this, I would really like to utilize the Data Annotations associated with each of the fields in the model, but I can't figure out how to access them.

Currently, I have set up field-level checks using information manually transcribed from the model, but this is very unsatisfactory since changing a StringLength setting in the model would mean remembering to update the validation routine separately.

I have googled every combination of search terms I can think of to try to find how to validate data without using the "SaveChanges()" function, but to no avail.

Surely I can't be the only person in the world to want to do something like this?

推荐答案

设置参数时应该能够出错:



You should be able to get errors when settings the parameters:

Employee emp = new Employee();

 try
 {
     emp.IdNumber = 9999999;
 }
 catch (ValidationException ex)
 {
     Console.WriteLine(ex.Message);
 }


如果所有更新都在事务中完成,那么任何未知错误都将导致数据无法保存。但是,如果你想要自定义消息,那么你必须先验证。



但请记住,在多用户数据库中,其他人可能会在验证和实际之间进行更改因此它可能并不总是有效。
If all updates are done in a transaction, then any undected error will cause the data to not be saved. However, if you want custom messages, then you have to validate first.

But remember that in multiusers database, someone else might make a change between your validation and the actual commit thus it might not always works.


这篇关于如何在不保存的情况下验证ASP.NET MVC实体框架中的数据的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆