使用DataAnnotations实现数据验证

 

System.ComponentModel.DataAnnotations命名空间中有一些特性类(如Required,Range),可以用来实现数据验证功能。

使用时先在文件头部引入命名空间:

 using System.ComponentModel.DataAnnotations;

namespace Test

{

  public class User

  {

     [Required] 

     public int UserId{set; get;}

 

    [Range(1,200,ErrorMessage="年龄超出范围")]

    public int Age(set; get;} 

  } 

 

此外,在使用了实体框架EF自动生成了类后,如果要使用DataAnnotations中的特性类,可以使用在分部类中添加内部元数据类型的方法来实现(假设EF已经自动创建了分部User类): 

新建==>,命名为User,然后改成分部类:为类添加MetadataType特性,并在类中添加一个内部类  //注意:两个User类必须在同一个命名空间中!!!

 using System.ComponentModel.DataAnnotations;

namespace Test

{

  [MetadataType(typeof(UserMD))]  //类名UserMD随便起,但需要和后面一致

  public particial class User

  {

    public class UserMD

  { 

     [Required] 

     public int UserId{set; get;}

 

    [Range(1,200,ErrorMessage="年龄超出范围")]

    public int Age(set; get;} 

   } 

  } 

 

原文地址:https://www.cnblogs.com/lgzslf/p/2127409.html