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

相关推荐
rising start1 天前
InsightEdu - 轻量智能学习平台
javascript·axios·css3·html5·fastapi·orm·dify
Kimhill张1 天前
.net core8 WPF 依赖注入(DI)
wpf·.netcore
wangl_922 天前
C# / .NET 在工业环境中的优势
开发语言·c#·.net·.netcore·.net core·visual studio
码农刚子3 天前
.NET 8 Web开发入门(四):注入燃料——Entity Framework Core 与 Code First 实战
数据库·orm·sql server
CSharp精选营3 天前
.NET 8 Web开发入门(四):注入燃料——Entity Framework Core 与 Code First 实战
orm·sql server·数据库迁移·ef core·entity framework core·crud操作·code first
阿kun要赚马内5 天前
后端数据操作组合:Pydantic与ORM
后端·python·orm·sqlalchemy
豆豆5 天前
信创环境下CMS国产化适配实践:以.NET Core路线为例的技术验证
.netcore·cms·信创·国产化·建站系统·内容管理系统·网站管理系统
时光追逐者5 天前
C#/.NET/.NET Core技术前沿周刊 | 第 70 期(2026年5.01-5.10)
c#·.net·.netcore
jump_jump7 天前
Drizzle 凭什么贴着 Go 跑——从设计哲学到热路径源码
数据库·性能优化·orm
L-影9 天前
常见的 ORM 工具
开发语言·数据库·fastapi·orm