net core 3 mysql_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.Data和MySql.Data.EntityFrameworkCore。

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

363a65b394198929faec6a6b3420ebce.png

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

a2a480b78ec106ff339d3abb25ec7478.png

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

01996d838554f30e39f7454cf31fd832.png

三、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 options) : base(options) { }

public DbSet movies { get; set; }

}

}

注意:如果需要使用DbContext需要引用using MySql.Data.EntityFrameworkCore类

【3】使用依赖注入将上下文注册为服务

public void ConfigureServices(IServiceCollection services)

{

services.AddControllers();

//声明连接字符串

var connection = Configuration["ConnectionStrings:MqStr"];

//使用连接字符串

services.AddDbContext(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

写在最后

原文:https://www.cnblogs.com/ZengJiaLin/p/11938585.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值