MVC + EF6-CodeFirst connect to the MySQL database and create tables and _Demo

VS2019 + MVC + EF6-CodeFirst connected MySQL

1, to prepare environmental (acquired by NuGet)

EntityFramework

MySql.Data.Entity

After the installation confirmation

2, add a class of students in the MVC-Model folder, behind it by using [Data Migration] to create a table in MySQL

     public class Student
    {
        public int ID { get; set; }

        public string LastName { get; set; }

        public string FirstMidName { get; set; } 
    }

3, create a data context (first introduced using System.Data.Entity;)

namespace EFToMysqlDemo
{
    //  [DbConfigurationType(typeof(MySql.Data.Entity.MySqlEFConfiguration))] 如果去掉这一句,EF自动创建数据库时会报错,而此时创建控制器又会报错,所以创建控制器的时候注销这句就可以了
    [DbConfigurationType(typeof(MySql.Data.Entity.MySqlEFConfiguration))]
    public class EFDemoContext:DbContext
    {
        static EFDemoContext()
        {
            //开发环境中,如果数据结构发生变化,需要重新建库,每次建库后要重新插入测试数据,可以用DropCreateDatabaseIfModelChanges类来实现(生成环境中请使用 Migrations做数据迁移)
            Database.SetInitializer(new DropCreateDatabaseIfModelChanges<EFDemoContext>());
        }
        public EFDemoContext():base("EFToMysqlCon") { }


        public DbSet<Student> Students { get; set; }
    }
}

4, the configuration file to add a link string

4.1 Specific parameters according to their modified accordingly

  <connectionStrings>
    <add name="EFToMysqlCon" connectionString="Data Source=127.0.0.1;port=3306;Initial Catalog=EFDemoDb;user id=root;password=123456;" providerName="MySql.Data.MySqlClient" />
  </connectionStrings>

5, data migration

5.1 Data Migration commonly used commands

命令1:启动EF数据迁移
Enable-Migrations -ContextTypeName 命名空间.上下文名称
命令2:创建迁移文件
Add-Migration 自定义名称
命令3:更新数据库
Update-Database

5.2 Open the Package Manager Console

5.3 (5.1) are performed in the common commands

View by Navicat MySQL 5.4

Guess you like

Origin www.cnblogs.com/zgsy/p/12637928.html