net core EF 链接mysql 数据库

这个主要是一个demo。就在一个工程里面写的


安装MySql.Data.EntityFrameworkCore

net core EF 链接mysql 数据库

 

增加DbContext 相当于程序与数据库的中间层
 public class IdentityDB: DbContext
    {
        public IdentityDB(DbContextOptions<IdentityDB> options)
            : base(options)
        {
            Database.EnsureCreated();
        }

        public DbSet<User> User { get; set; }
    }

    构造函数里面是  新建数据库的。首次运行如果没有数据库会新建 如果有什么也不干

    下面DbSet<>是映射的数据库表

把dbContext 注册到容器
 public void ConfigureServices(IServiceCollection services)
        {
            var mysql = Configuration.GetConnectionString("mysql");
            services.AddDbContext<IdentityDB>(o => o.UseMySQL(mysql));
         }

    

链接字符串
"mysql": "Server=localhost;database=identity;uid=root;pwd=abc123;Character Set=utf8"

      

Character Set=utf8一定要加 要不然中文会乱码