更新时间:2023-02-08 16:52:11
更新:由于这还是比较受欢迎的,我创建这个博客帖子
Update: As this is still relatively popular, I have created a blog post on this.
http://jnye.co/Posts/19/adding-validation-to-models-created-by-entity-framework-database-first-c
如果您想验证的模型,而不是使用的ViewModels,使用部分类来定义属性验证。例如:
If you want to validate your models, and not use viewModels, use partial classes to define validation attributes. For example:
假设你有一个像
public class User {
public string Name { get; set; }
}
如果你想要把一个字符串长度的验证就可以了,你需要创建一个分部类和利用 MetadataTypeAttribute
(此住在System.ComponentModel.DataAnnotations)
If you wanted to put a string length validator on it you would need to create a partial class and utilise the MetadataTypeAttribute
(this lives in System.ComponentModel.DataAnnotations)
下面的类应该在自己单独的文件中定义的不可以放在同一个文件作为自动生成的模型。
The following classes should be defined in their own separate file, NOT put in the same file as your auto generated models.
[MetadataTypeAttribute(typeof(UserMetadata))]
public partial class User {
}
您然后定义在 UserMetadata code>类的验证如下:
You then define your validation in the UserMetadata
class as follows
public class UserMetadata{
[StringLength(50)]
public string Name {get; set;}
}
修改
我刚刚发现这个文章,其中介绍了在一个小更详细的解决方案
的http://themonitoringguy.com/tips-tricks/validating-microsoft-entity-framework-objects-c-mvc/
I just found this article which explains the solution in a little more detail http://themonitoringguy.com/tips-tricks/validating-microsoft-entity-framework-objects-c-mvc/