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

相关推荐
CSharp精选营15 小时前
ASP.NET Core EFCore 属性配置与DbContext 详解
.net core·efcore·dbcontext
满怀10151 天前
【Django全栈开发实战】从零构建企业级Web应用
前端·python·django·orm·web开发·前后端分离
编程乐趣5 天前
基于.Net Core开发的GraphQL开源项目
后端·.netcore·graphql
吾门6 天前
机器视觉开发教程——C#如何封装海康工业相机SDK调用OpenCV/YOLO/VisionPro/Halcon算法
图像处理·opencv·计算机视觉·c#·.net·.netcore·visual studio
xiangji6 天前
ShadowSql之开源不易
orm·dapper·sqlbuilder
Kookoos7 天前
ABP vNext + EF Core 实战性能调优指南
数据库·后端·c#·.net·.netcore
[email protected]8 天前
ASP.NET Core 中实现 Markdown 渲染中间件
后端·中间件·asp.net·.netcore
吃瓜日常9 天前
ABP项目发布到IIS流程
c#·.netcore
[email protected]10 天前
ASP.NET Core 中间件
后端·中间件·asp.net·.netcore
[email protected]11 天前
ASP.NET Core 请求限速的ActionFilter
后端·asp.net·.netcore