Mysql实现EF Core CodeFirst实现

一、引用包

Microsoft.EntityFrameworkCore.Tools
Pomelo.EntityFrameworkCore.MySql

二、常用命令

1、Add-Migration (版本号) 创建新的CodeFirst文件
2、Update-Database 更新数据库 

三、代码实现

   /// <summary>
    /// 系统用户
    /// </summary>
    [Table("SysUser")]
    public class SysUser
    {
        /// <summary>
        /// 主键ID
        /// </summary>
        [Key]
        [DatabaseGenerated(DatabaseGeneratedOption.Identity)]
        public int Id { get; set; }
        /// <summary>
        /// 用户ID
        /// </summary>
        [Column("UserId")]
        [MinLength(6)]
        [MaxLength(20)]
        public string UserId { get; set; }
        /// <summary>
        /// 用户密码
        /// </summary>
        [Column("Pwd")]
        //[MinLength(6)]
        //[MaxLength(20)]
        [StringLength(20, MinimumLength = 6)]
        public string Pwd { get; set; }
        /// <summary>
        /// 用户姓名
        /// </summary>
        [Required]
        [StringLength(20, MinimumLength = 6)]
       
        [Column("UserName")]
        public string UserName { get; set; }
        [NotMapped]
        public string dd { get;set; }
    }

配置

     /// <summary>
   /// 系统数据上下文 /// </summary> public class SysDbContext : DbContext { /// <summary> /// 系统数据上下文 /// </summary> /// <param name="options">配置参数</param> public SysDbContext(DbContextOptions options) : base(options) { } /// <summary> /// 用户信息 /// </summary> public DbSet<SysUser> Users { get; set; } }
// 配置
var connectionString = "Data Source= 192.168.0.34 ; Database= SysManage; User ID= lzy ; Password=438520Qiu; pooling=true ; port= 3306; sslmode=none ; CharSet =utf8;allowPublicKeyRetrieval=true;"; builder.Services.AddDbContext<SysDbContext>((option) => { option.UseMySql(connectionString, new MySqlServerVersion(new Version(8, 0, 27))); });

 

posted @ 2023-10-07 23:24  lzy1666  阅读(59)  评论(0编辑  收藏  举报