写在前面
在前一小节中,我们创建了基于RESFULL
风格的服务。这个小节,尝试使用CodeFirst+MySql 的方式实现数据迁移。
一、开发环境
【1】运行环境:win10 家庭版
【2】开发工具:Visual Studio 2019 16.3.10
【3】数据库:MySql 8.0.0
二、前期准备
因为使用的是MySQL
的数据库。所以,需要下载MySql.Data
和MySql.Data.EntityFrameworkCore
。
【1】选择工具
->NuGet包管理器
->'NuGet程序包'。如图所示:
【2】搜索MySql.Data
,下载8.0.18
版本。如图所示:
【3】搜索MySql.Data.EntityFrameworkCore
,下载8.0.18
版本。如图所示:
三、CodeFirst 步骤
【1】创建电影类Movie
类
using System; using System.ComponentModel; using System.ComponentModel.DataAnnotations; using System.ComponentModel.DataAnnotations.Schema; namespace netCoreWebapi001 { public class movie { [Description("主键")] [Key] [DatabaseGenerated(DatabaseGeneratedOption.Identity)] public int Id { get; set; } [Description("电影名称")] public string Title { get; set; } [Description("日期")] public DateTime ReleaseDate { get; set; } [Description("类型")] public string Genre { get; set; } [Description("价格")] public decimal Price { get; set; } } }
【2】创建上下类DatabaseContext
需要引用using MySql.Data.EntityFrameworkCore
类
using MySql.Data.EntityFrameworkCore; namespace netCoreWebapi001 { public class DatabaseContext: DbContext { public DatabaseContext(DbContextOptions<DatabaseContext> options) : base(options) { } public DbSet<movie> movies { get; set; } } }
注意:如果需要使用DbContext
需要引用using MySql.Data.EntityFrameworkCore
类
【3】使用依赖注入将上下文注册为服务
public void ConfigureServices(IServiceCollection services) { services.AddControllers(); //声明连接字符串 var connection = Configuration["ConnectionStrings:MqStr"]; //使用连接字符串 services.AddDbContext<DatabaseContext>(options => { options.UseMySQL(connection); }); }
注意:使用UseMySQL
时,需要引用using Microsoft.EntityFrameworkCore
【3】修改appsettings.json
配置信息
//应用程序配置文件,类似于ASP.NET MVC应用程序中的Web.config配置文件 { "Logging": { "LogLevel": { "Default": "Information", "Microsoft": "Warning", "Microsoft.Hosting.Lifetime": "Information" } }, "AllowedHosts": "*", "ConnectionStrings": { //例如:连接字符串 "MqStr": "Data Source=localhost;port=3306;database=TextNetCoreWebApi;User Id=root;Password=root" } }
【5】迁移或创建数据库
使用操作命令迁移或者创建数据库
工具
->NuGet 包管理器
>程序包管理器控制台
执行以下命令:
//1.删除Migrations文件夹 Enable-Migrations //2.初始化数据库 Add-Migration Initial //3.更新数据库 Update-Database