Now I have a create form in C# MVC it's called "course" and I have custom validation called courseValidation
现在我在C#MVC中有一个创建表单,它被称为“课程”,我有自定义验证,名为courseValidation
I get the error:
我收到错误:
Validation failed for one or more entities.
See 'EntityValidationErrors' property for more details.
Models "courses"
[Required]
[courseValidation()]
public string courseName { set; get; }
Controller "courseController"
[HttpPost]
public ActionResult Create(Models.courses course)
{
course.userId = 13;
db.courses.Add(course);
db.SaveChanges();
return View();
}
and my custom validation courseValidation
和我的自定义验证课程验证
public override bool IsValid(object value)
{
int query = (from res in db.courses
where res.courseName == value.ToString()
select res).Count();
if (query == 0)
{
return true;
}
else
{
return false ;
}
}
I always have the error in savechanges()
, but when I removed my custom validation from the model there is no error happening.
我总是在savechanges()中有错误,但是当我从模型中删除自定义验证时,没有发生错误。
1 个解决方案
#1
5
What you're doing is not validation, but verification. Avoid heavy logic with dependencies in attribute code.
你所做的不是验证,而是验证。避免在属性代码中具有依赖性的重逻辑。
Validation is concerned with "static" matters: data formats, lengths, very basic logic, the kind of things you'd use a regular expression for. That is: the data is valid, but not necessarily verified.
验证涉及“静态”问题:数据格式,长度,非常基本的逻辑,你使用正则表达式的东西。即:数据有效,但不一定经过验证。
Verification is where you verify the provided data, this requires you to connect to a database or other external data to check it out, due to the extra legwork required it is an expensive process and should appear as part of your main business logic (as these are business rules that you're executing).
验证是验证提供的数据的地方,这需要您连接到数据库或其他外部数据以进行检查,因为需要额外的工作量,这是一个昂贵的过程,应该作为主要业务逻辑的一部分出现(如这些是您正在执行的业务规则。
So your ViewModel should look like:
因此,您的ViewModel应如下所示:
[Required]
public String CourseName { set; get; }
And your Controller should look like:
你的控制器看起来像:
[HttpPost]
public ActionResult Create(CoursesViewModel viewModel)
{
if( !this.IsCoursesViewModelValid( this.db, viewModel ) ) {
this.ModelState.AddError("some error message");
return this.View();
}
DBCourse dbCourse = new DBCourse();
dbCourse.Name = viewModel.CourseName;
db.Courses.Add( dbCourse );
db.SaveChanges();
return this.View();
}
private Boolean IsCoursesViewModelValid(DataContext db, CoursesViewModel viewModel) {
return db.Courses.Where( dbC => dbC.CourseName == viewModel.CourseName ).Count() == 0;
}
Important note: Do not use DB Entity classes as ViewModels! Your ViewModels should be separate POCO classes that contain only state and data for the view. There are numerous reasons not to use DB Entities as ViewModels:
重要说明:不要将DB实体类用作ViewModels!您的ViewModel应该是单独的POCO类,它们只包含视图的状态和数据。有许多理由不将DB实体用作ViewModels:
- Security. A malicious user could set any entity data member by taking advantage of default model-binding behaviour
- It keeps the separation-of-concerns. Your view should know nothing of your database. If you refactor your DB schema you'll need to update your views because the references will be broken
- Data members and View-model fields don't match: consider a view for a
Users
table. Your form would want two password fields ("Enter a new password" and "Confirm your password") which should be text, but your database won't have a password column, it will have a binaryPasswordHash
andPasswordSalt
column, which doesn't match your form at all.
安全。恶意用户可以通过利用默认的模型绑定行为来设置任何实体数据成员
它保持了关注点的分离。您的视图应该对您的数据库一无所知。如果您重构数据库架构,则需要更新视图,因为引用将被破坏
数据成员和视图模型字段不匹配:考虑Users表的视图。您的表单需要两个密码字段(“输入新密码”和“确认您的密码”),这些字段应该是文本,但您的数据库将没有密码列,它将具有二进制PasswordHash和PasswordSalt列,它不会完全匹配你的表格。
#1
5
What you're doing is not validation, but verification. Avoid heavy logic with dependencies in attribute code.
你所做的不是验证,而是验证。避免在属性代码中具有依赖性的重逻辑。
Validation is concerned with "static" matters: data formats, lengths, very basic logic, the kind of things you'd use a regular expression for. That is: the data is valid, but not necessarily verified.
验证涉及“静态”问题:数据格式,长度,非常基本的逻辑,你使用正则表达式的东西。即:数据有效,但不一定经过验证。
Verification is where you verify the provided data, this requires you to connect to a database or other external data to check it out, due to the extra legwork required it is an expensive process and should appear as part of your main business logic (as these are business rules that you're executing).
验证是验证提供的数据的地方,这需要您连接到数据库或其他外部数据以进行检查,因为需要额外的工作量,这是一个昂贵的过程,应该作为主要业务逻辑的一部分出现(如这些是您正在执行的业务规则。
So your ViewModel should look like:
因此,您的ViewModel应如下所示:
[Required]
public String CourseName { set; get; }
And your Controller should look like:
你的控制器看起来像:
[HttpPost]
public ActionResult Create(CoursesViewModel viewModel)
{
if( !this.IsCoursesViewModelValid( this.db, viewModel ) ) {
this.ModelState.AddError("some error message");
return this.View();
}
DBCourse dbCourse = new DBCourse();
dbCourse.Name = viewModel.CourseName;
db.Courses.Add( dbCourse );
db.SaveChanges();
return this.View();
}
private Boolean IsCoursesViewModelValid(DataContext db, CoursesViewModel viewModel) {
return db.Courses.Where( dbC => dbC.CourseName == viewModel.CourseName ).Count() == 0;
}
Important note: Do not use DB Entity classes as ViewModels! Your ViewModels should be separate POCO classes that contain only state and data for the view. There are numerous reasons not to use DB Entities as ViewModels:
重要说明:不要将DB实体类用作ViewModels!您的ViewModel应该是单独的POCO类,它们只包含视图的状态和数据。有许多理由不将DB实体用作ViewModels:
- Security. A malicious user could set any entity data member by taking advantage of default model-binding behaviour
- It keeps the separation-of-concerns. Your view should know nothing of your database. If you refactor your DB schema you'll need to update your views because the references will be broken
- Data members and View-model fields don't match: consider a view for a
Users
table. Your form would want two password fields ("Enter a new password" and "Confirm your password") which should be text, but your database won't have a password column, it will have a binaryPasswordHash
andPasswordSalt
column, which doesn't match your form at all.
安全。恶意用户可以通过利用默认的模型绑定行为来设置任何实体数据成员
它保持了关注点的分离。您的视图应该对您的数据库一无所知。如果您重构数据库架构,则需要更新视图,因为引用将被破坏
数据成员和视图模型字段不匹配:考虑Users表的视图。您的表单需要两个密码字段(“输入新密码”和“确认您的密码”),这些字段应该是文本,但您的数据库将没有密码列,它将具有二进制PasswordHash和PasswordSalt列,它不会完全匹配你的表格。