ASP.NET Core 3.0 WebApi 系列【2】.Net Core + CodeFirst + MySql 实现数据的迁移

写在前面


在前一小节中,我们创建了基于RESFULL风格的服务。这个小节,尝试使用CodeFirst+MySql 的方式实现数据迁移。

一、开发环境


【1】运行环境:win10 家庭版

【2】开发工具:Visual Studio 2019 16.3.10

【3】数据库:MySql 8.0.0

二、前期准备


因为使用的是MySQL的数据库。所以,需要下载MySql.DataMySql.Data.EntityFrameworkCore

【1】选择工具->NuGet包管理器->'NuGet程序包'。如图所示:

【2】搜索MySql.Data,下载8.0.18版本。如图所示:

【3】搜索MySql.Data.EntityFrameworkCore,下载8.0.18版本。如图所示:

扫描二维码关注公众号,回复: 7987730 查看本文章

三、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 

写在最后


参考文档1

猜你喜欢

转载自www.cnblogs.com/ZengJiaLin/p/11938585.html