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

相关推荐
MoFe13 天前
【.net core】【NPOI】读取表格信息(处理合并行表格数据)
.netcore
csdn_aspnet3 天前
在 .NET Core 中实现基于策略和基于角色的授权
.netcore·role·policy
The Sheep 20233 天前
.NetCore MVC
mvc·.netcore
一包烟电脑面前做一天4 天前
.NetCore下Ocelot + Nacos 实现负载均衡
nacos·负载均衡·.netcore·ocelot·ocelot集成nacos
一个帅气昵称啊4 天前
NetCoreKevin-DDD-微服务-WebApi-AI智能体、AISK集成、MCP协议服务、SignalR、Quartz 框架-16-部署与基础设施
微服务·云原生·架构·系统架构·.netcore
忧郁的蛋~4 天前
在.NET标准库中进行数据验证的方法
后端·c#·asp.net·.net·.netcore
willhuo5 天前
学生请假就餐系统
运维·服务器·.netcore
一包烟电脑面前做一天6 天前
.NetCore 接入 Nacos,实现配置中心和服务注册
nacos·.netcore·服务注册发现·配置中心
切糕师学AI8 天前
.Net Core Web 架构(管道机制)的底层实现
中间件·系统架构·kestrel·mvc·.netcore·路由·请求管道
余衫马11 天前
Mysql 5.7 与 SqlSugar 5.X 整合开发实战
mysql·c#·orm·sqlsugar