net core 2.1 EFcore CodeFirst 使用Mysql数据库

一、在nuget中分别安装1、 Pomelo.EntityFrameworkCore.MySql

                               2、Pomelo.EntityFrameworkCore.MySql.Design

                               3、Microsoft.EntityFrameworkCore.Tools

 

net core 2.1 EFcore CodeFirst 使用Mysql数据库

二、创建一个模型类 Person

public class Person
    {
       public long Id { get; set; }
        public string Name { get; set; }
        public int Age { get; set; }
        public bool? Gender { get; set; }
    }

三、创建数据上下文MyDbContext

 public class MyDbContext : DbContext
    {
        public DbSet<Person> Persons { get; set; }
        protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
        {
            base.OnConfiguring(optionsBuilder);
            optionsBuilder.UseMySQL("Server=127.0.0.1;database=testdb;uid=root;password=pwd123456;TreatTinyAsBoolean=true");//配置连接字符串 必须TreatTinyAsBoolean=true  如果不加 bool类型会自动转化成bit类型 疯狂报错
        }
        protected override void OnModelCreating(ModelBuilder modelBuilder)
        {
            base.OnModelCreating(modelBuilder);
            var etPerson = modelBuilder.Entity<Person>().ToTable("t_persons");
            etPerson.Property(e => e.Age).IsRequired();//不写IsRequired,默认为可空
            etPerson.Property(e => e.Gender).IsRequired();
            etPerson.Property(e => e.Name).HasMaxLength(20).IsRequired();
        }

    }

四、开启迁移并生产数据库

在程序包控制台中输入如下指令

1、Enable-Migrations 

net core 2.1 EFcore CodeFirst 使用Mysql数据库

2、Add-Migration Initial

net core 2.1 EFcore CodeFirst 使用Mysql数据库

指令完成之后生成如下文件

net core 2.1 EFcore CodeFirst 使用Mysql数据库

3、Update-DataBase

net core 2.1 EFcore CodeFirst 使用Mysql数据库

指令执行完成之后,相应的数据库和表 自动生成。

net core 2.1 EFcore CodeFirst 使用Mysql数据库

net core 2.1 EFcore CodeFirst 使用Mysql数据库