efCore+Mysql8,使用及表的迁移

1.安装 Nuget 包

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

2.MVC 框架搭出来

models

cs 复制代码
using System.ComponentModel.DataAnnotations;
using System.ComponentModel.DataAnnotations.Schema;

namespace ShuYiTest.Models;
[Table("User")]
public class UserInfo
{
    [Key]
    public string ID { get; set; }
    public string UserName { get; set; }

    public string Password { get; set; }

    public string PhoneNumber { get; set; }

}

Controller

cs 复制代码
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
using ShuYiTest.helper;
using ShuYiTest.Models;

namespace ShuYiTest.Controller
{

    [Route("[controller]/[action]")]
    [ApiController]
    public class UserController : ControllerBase
    {
        [HttpPost]
        public IActionResult GetUser(UserInfo user)
        {

            Console.WriteLine("Success");
        }
    }
}

3.创建 DbContext 类

cs 复制代码
using Microsoft.EntityFrameworkCore;
using ShuYiTest.Models;

namespace ShuYiTest.helper;

public class EFContext:DbContext
{

    public EFContext()
    {

    }

    public DbSet<UserInfo> Persons { get; set; }

    IConfiguration configuration = new ConfigurationBuilder()
            .AddJsonFile("appsettings.json", optional: true, reloadOnChange: true)
            .Build();

    protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
    {
        optionsBuilder.UseMySql(configuration["ConnectionStrings:MysqlConnection"],new MySqlServerVersion(new Version(8,0,37)));
    }
}

4.appsettings.json 中配置连接字段

json 复制代码
"ConnectionStrings": {
    "MysqlConnection": "server=localhost;port=3306;user=czm;password=Chenzhiming11.27;database=test"
  },

5.使用 ef 进行表的迁移

1.dotnet ef migrations add InitialCreate//创建迁移

2.dotnet ef database update//应用迁移

3.dotnet ef migrations list//查看迁移历史

6.efCore 的使用

https://learn.microsoft.com/zh-cn/ef/core

相关推荐
刘梦凡呀1 天前
C# .NET Core 批量下载文件
windows·c#·.netcore
Zhen (Evan) Wang2 天前
.NET 6 WPF 利用CefSharp.Wpf.NETCore显示PDF文件
.net·wpf·.netcore
时光追逐者2 天前
C#/.NET/.NET Core拾遗补漏合集(25年4月更新)
c#·.net·.netcore
追雨潮2 天前
.net core 项目快速接入Coze智能体-开箱即用-第2节
.netcore
追雨潮3 天前
.net core 项目快速接入Coze智能体-开箱即用-全局说明
.netcore·ai编程
时光追逐者3 天前
C#/.NET/.NET Core技术前沿周刊 | 第 35 期(2025年4.14-4.20)
c#·.net·.netcore
全栈小54 天前
【C#】.net core 6.0调用MVC API接口时,提示Unsupported Media Type,状态码415
c#·mvc·.netcore
猫霸4 天前
理解.NET Core中的配置Configuration
html·.netcore·xhtml
MoFe14 天前
【.net core】【watercloud】数据库连接报错问题
数据库·.netcore
csdn_aspnet4 天前
Windows .NET Core 应用程序部署到 IIS 解决首次访问加载慢的问题
iis·.netcore