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

相关推荐
大尚来也19 小时前
双库协同,各取所长:.NET Core 中 PostgreSQL 与 SQLite 的优雅融合实战
postgresql·sqlite·.netcore
吹牛不交税1 天前
admin.net-v2 框架使用笔记-netcore8.0/10.0版
vue.js·.netcore
雪碧聊技术4 天前
ORM简介、安装、使用流程
fastapi·orm·基础代码编写
雪碧聊技术4 天前
ORM-查询
fastapi·orm·查询
张3蜂5 天前
java springboot2.0 api ;.netcore8 api ;python GunicornAPI ,哪种更强?请从多个维度,对比分析
java·python·.netcore
切糕师学AI6 天前
.NET Core Web 中的健康检查端点(Health Check Endpoint)
前端·kubernetes·.netcore
xdpcxq10296 天前
.NET Core 双数据库 PostgreSQL 与 SQLite 和平共处
数据库·postgresql·.netcore
csdn_aspnet10 天前
.Net Core — Cookie 身份验证
.netcore·cookie
csdn_aspnet10 天前
在 ASP.NET Core 中实现 Cookie 身份验证
后端·asp.net·.netcore·cookie