如何避免MVC Model First 设计时添加的DataAnnotation被覆盖掉

  结合多方资料做一系统,发现Code First中所有代码要自己写,无法自动生成(暂时没有找到方法,有知道的大能,给指点一下,好像在NuGet中有一个插件可以直接从数据库中生成Code First所需类,不过没有研究.),所有采用Model First,但是Model First中自动生成的文件没有添加DataAnnotation(同样求指点),所以在自动生成后再自行添加DataAnnotation,这时问题又出来了.每次修改Model后,就把原来的给覆盖了.得重新添加DataAnnotation.

  经查看资料Validation with the Data Annotation Validators 发现是这样解决的.现记录下来,以备后查.

  第一步:在自动生成Model文件的文件夹中添加同名的分部类(在类名前添加关键字 partial  ),如:

自动生成的类为 "User" 类, 要写成    public partial class User 

  第二步:在它前面添加[MetadataType(typeof(UserDataAnnotation))],其中UserDataAnnotation 是要面要新建的另一个类,这个类就是我们要自定义添加的内容.

  第三步,添加 UserDataAnnotation  类,然后添加相应内容

代码如下:

//------------------------------------------------------------------------------
// <auto-generated>
//     此代码已从模板生成。
//
//     手动更改此文件可能导致应用程序出现意外的行为。
//     如果重新生成代码,将覆盖对此文件的手动更改。
// </auto-generated>
//------------------------------------------------------------------------------

namespace DataModel
{
    using System;
    using System.Collections.Generic;
    
    public partial class Longger_User
    {
        publicUser()
        {
            this.RoleID = new HashSet<Role>();
        }
    
        public int UserID { get; set; }
        public string UserName { get; set; }
        public string DisplayName { get; set; }
        public string Password { get; set; }
        public string Email { get; set; }
        public Status Status { get; set; }
        public Nullable<System.DateTime> RegistrationTime { get; set; }
        public Nullable<System.DateTime> LoginTime { get; set; }
        public string LoginIP { get; set; }
    
        public virtual ICollection<Role> RoleID { get; set; }
      }
}
自动生成的类
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;

namespace DataModel
{

    // 这一句代码最重要
    //UserDataAnnotation,必须是下面要添加的类名.
    [MetadataType(typeof(UserDataAnnotation))] 

     //这个必须要和自动生成的类同名,而且必须要在同一命名空间下
    public partial class User   
    {
    }

    //这个类名必须是   [MetadataType(typeof(UserDataAnnotation))] 里面的类名
    public partial class UserDataAnnotation
    {
        [Display(Name="用户名")]
        public string UserName
        {
            get;
            set;
        }

        [Display( Name = "电子邮箱" )]
        [DataType( DataType.EmailAddress,ErrorMessage="邮箱格式不正确")]
        public string Email
        {
            get;
            set;
        }

        [Display(Name="显示名")]
        [StringLength(20,MinimumLength=2,ErrorMessage="{2}到{1}个字符")]
        public string DisplayName
        {
            get;
            set;
        }

        [Display(Name="用户组编号")]
        public virtual ICollection<Longger_Role> RoleID
        {
            get;
            set;
        }
    }
}
新添加的内容

参考资料:Validation with the Data Annotation Validators

原文地址:https://www.cnblogs.com/fcu3dx/p/3768556.html