在vs mac中基于.Net6 Mvc EFcore生成数据表(mysql版)

脑子抽筋尝试在vs 2022 for mac 版本中编写Mvc应用,真是踩的一堆坑,试了大半天终于将mysql数据库连接配置完成,(基于code firts)

---------------------------环境------------------------------

操作系统:macOS monterey 12.1(M1)

mysql数据库:8.0.28-arm64

开发工具:Visual Studio 2022 for Mac (Preview)(尝鲜。。。bug真多一言难尽哈哈哈哈)

---------------------------------------------------------------

开始溜达起来:

一、创建.NET6 MVC应用

二、导入相关NuGet包

Microsoft.EntityFrameworkCore
Microsoft.EntityFrameworkCore.Tools
Pomelo.EntityFrameworkCore.MySql

三、配置数据连接并迁移

(1)构造数据连接类

        新建Data文件夹->文件夹中新增空白类->添加如下代码

using System;
using Microsoft.EntityFrameworkCore;
namespace EFdome.Data
{
	//原始生成的类代码
	//public class MyDbContext
	//{
	//	public MyDbContext()
	//	{

	//	}
	//}


	//手动改造后的类代码
	public class MyDbContext:DbContext
	{
		public MyDbContext(DbContextOptions<MyDbContext> options):base(options)
		{

		}
	}
}

(2)修改appsettings.json配置类

    增加ConnectionStrings

{
  "Logging": {
    "LogLevel": {
      "Default": "Information",
      "Microsoft.AspNetCore": "Warning"
    }
  },
  "AllowedHosts": "*",
  "ConnectionStrings": {
    "MySql": "server=localhost;user=root;database=mvcTest;port=3306;password=123456"
  }
}

(3)修改Program.cs

    注.Net6 生成的MVC应用中Startup.cs已被去掉相关代码以整合到Program.cs中

    所以在Program中做如下修改

//新增引用
using Microsoft.EntityFrameworkCore;
using StudentMVC.Data;

var builder = WebApplication.CreateBuilder(args);

// Add services to the container.
builder.Services.AddControllersWithViews();


//新增数据库连接读取
builder.Services.AddDbContext<MyDbContext>(options => options.UseMySql(
    builder.Configuration.GetConnectionString("MySql"),
    ServerVersion.AutoDetect(builder.Configuration.GetConnectionString("MySql"))));
//builder.Services.AddScoped(<DbContext, MyDbContext>);


var app = builder.Build();

// Configure the HTTP request pipeline.
if (!app.Environment.IsDevelopment())
{
    app.UseExceptionHandler("/Home/Error");
}
app.UseStaticFiles();

app.UseRouting();

app.UseAuthorization();

app.MapControllerRoute(
    name: "default",
    pattern: "{controller=Home}/{action=Index}/{id?}");

app.Run();

(4)新增数据表模型

    在Models文件夹中新建两个类LoginModel、EmployeeModel

using System;
using System.ComponentModel.DataAnnotations;

namespace EFdome.Models
{
	public class LoginModel
	{
		[Key]
		public int ID { get; set; }

		[Required]
		[Display(Name ="登陆账号")]
		public string LoginName { get; set; }

		[Display(Name ="登陆密钥")]
		public string LoginPwd { get; set; }

		[Display(Name ="账号状态")]
		public int UserStatus { get; set; }

		[Display(Name ="创建时间")]
		public DateTime? CreateTime { get; set; }

		[Display(Name ="最近一次登陆时间")]
		public DateTime? LoginTime { get; set; }
	}
}
using System;
using System.ComponentModel.DataAnnotations;

namespace EFdome.Models
{
	public class Employee
	{
		[Key]
		public int ID { get; set; }

		[Display(Name ="用户姓名")]
		public string UserName { get; set; }

		[Display(Name = "用户性别")]
		public string? UserSex { get; set; }

		[Display(Name = "用户年龄")]
		public string? UserAge { get; set; }

		[Display(Name = "用户电话")]
		public string? UserPhone { get; set; }

		[Display(Name = "用户状态")]
		public int UserStatus { get; set; }

		[Display(Name = "用户创建时间")]
		public DateTime? CreateTime { get; set; }

		[Display(Name = "用户住址")]
		public string? HomePath { get; set; }
	}
}

    在连接器中注册这两个模型

using System;
using EFdome.Models;
using Microsoft.EntityFrameworkCore;
namespace EFdome.Data
{
	//原始生成的类代码
	//public class MyDbContext
	//{
	//	public MyDbContext()
	//	{

	//	}
	//}


	//手动改造后的类代码
	public class MyDbContext : DbContext
	{
		public MyDbContext(DbContextOptions<MyDbContext> options) : base(options)
		{

		}


		//在连接器中注册这两个模型
		public DbSet<LoginModel> Logins { get; set; }

		public DbSet<EmployeeModel> Employees { get; set; }
	}

	
}

(5)用过ef工具进行数据迁移

    注:在VS for Mac 中包控制器是不能进行输入指令操作的,刚开始不知道真实想到头秃

    在VS for Mac 中打开终端通过dotnet指令操作     Path:点击“查看”-》“终端”。 

    踩坑....VS终端中切换拼音输入法在点击字母输入VS就崩溃了,异常提交地址:

Visual Studio Feedbackicon-default.png?t=M4ADhttps://developercommunity.visualstudio.com/t/%E7%BB%88%E7%AB%AF%E8%BE%93%E5%85%A5%E5%AD%97%E6%AF%8D%E7%B1%BB%E5%9E%8B%E6%9C%89%E9%97%AE%E9%A2%98-Typing-using-an-IME-in-the/10042362?space=41&q=244009012

    输入dotnet指令查看是否安装ef(Microsoft.EntityFrameworkCore.Tools)

dotnet ef --version

   cd 到项目的根目录执行以下指令

 dotnet ef migrations add '迁移名称'
winkk@wenwenwendeMacBook-Pro ef % dotnet ef migrations add 'EFdome1'
Build started...
Build succeeded.
info: Microsoft.EntityFrameworkCore.Infrastructure[10403]
      Entity Framework Core 6.0.5 initialized 'MyDbContext' using provider 'Pomelo.EntityFrameworkCore.MySql:6.0.1' with options: ServerVersion 8.0.28-mysql 
Done. To undo this action, use 'ef migrations remove'

  出现以上信息证明迁移成功,然后执行数据库更新指令创建对应的表

 dotnet ef database update
winkk@wenwenwendeMacBook-Pro ef % dotnet ef database update
Build started...
Build succeeded.
info: Microsoft.EntityFrameworkCore.Infrastructure[10403]
      Entity Framework Core 6.0.5 initialized 'MyDbContext' using provider 'Pomelo.EntityFrameworkCore.MySql:6.0.1' with options: ServerVersion 8.0.28-mysql 
info: Microsoft.EntityFrameworkCore.Database.Command[20101]
      Executed DbCommand (19ms) [Parameters=[], CommandType='Text', CommandTimeout='30']
      SELECT 1 FROM INFORMATION_SCHEMA.TABLES WHERE TABLE_SCHEMA='mvcTest' AND TABLE_NAME='__EFMigrationsHistory';
info: Microsoft.EntityFrameworkCore.Database.Command[20101]
      Executed DbCommand (22ms) [Parameters=[], CommandType='Text', CommandTimeout='30']
      CREATE TABLE `__EFMigrationsHistory` (
          `MigrationId` varchar(150) CHARACTER SET utf8mb4 NOT NULL,
          `ProductVersion` varchar(32) CHARACTER SET utf8mb4 NOT NULL,
          CONSTRAINT `PK___EFMigrationsHistory` PRIMARY KEY (`MigrationId`)
      ) CHARACTER SET=utf8mb4;
info: Microsoft.EntityFrameworkCore.Database.Command[20101]
      Executed DbCommand (4ms) [Parameters=[], CommandType='Text', CommandTimeout='30']
      SELECT 1 FROM INFORMATION_SCHEMA.TABLES WHERE TABLE_SCHEMA='mvcTest' AND TABLE_NAME='__EFMigrationsHistory';
info: Microsoft.EntityFrameworkCore.Database.Command[20101]
      Executed DbCommand (4ms) [Parameters=[], CommandType='Text', CommandTimeout='30']
      SELECT `MigrationId`, `ProductVersion`
      FROM `__EFMigrationsHistory`
      ORDER BY `MigrationId`;
info: Microsoft.EntityFrameworkCore.Migrations[20402]
      Applying migration '20220515095132_EFdome1'.
Applying migration '20220515095132_EFdome1'.
info: Microsoft.EntityFrameworkCore.Database.Command[20101]
      Executed DbCommand (1ms) [Parameters=[], CommandType='Text', CommandTimeout='30']
      ALTER DATABASE CHARACTER SET utf8mb4;
info: Microsoft.EntityFrameworkCore.Database.Command[20101]
      Executed DbCommand (5ms) [Parameters=[], CommandType='Text', CommandTimeout='30']
      CREATE TABLE `Employees` (
          `ID` int NOT NULL AUTO_INCREMENT,
          `UserName` longtext CHARACTER SET utf8mb4 NOT NULL,
          `UserSex` longtext CHARACTER SET utf8mb4 NULL,
          `UserAge` longtext CHARACTER SET utf8mb4 NULL,
          `UserPhone` longtext CHARACTER SET utf8mb4 NULL,
          `UserStatus` int NOT NULL,
          `CreateTime` datetime(6) NULL,
          `HomePath` longtext CHARACTER SET utf8mb4 NULL,
          CONSTRAINT `PK_Employees` PRIMARY KEY (`ID`)
      ) CHARACTER SET=utf8mb4;
info: Microsoft.EntityFrameworkCore.Database.Command[20101]
      Executed DbCommand (5ms) [Parameters=[], CommandType='Text', CommandTimeout='30']
      CREATE TABLE `Logins` (
          `ID` int NOT NULL AUTO_INCREMENT,
          `LoginName` longtext CHARACTER SET utf8mb4 NOT NULL,
          `LoginPwd` longtext CHARACTER SET utf8mb4 NOT NULL,
          `UserStatus` int NOT NULL,
          `CreateTime` datetime(6) NULL,
          `LoginTime` datetime(6) NULL,
          CONSTRAINT `PK_Logins` PRIMARY KEY (`ID`)
      ) CHARACTER SET=utf8mb4;
info: Microsoft.EntityFrameworkCore.Database.Command[20101]
      Executed DbCommand (1ms) [Parameters=[], CommandType='Text', CommandTimeout='30']
      INSERT INTO `__EFMigrationsHistory` (`MigrationId`, `ProductVersion`)
      VALUES ('20220515095132_EFdome1', '6.0.5');
Done.

 输出以上信息则会在对应的数据库中生成相应的表(Employess、Logins) 如图所示