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

相关推荐
dephixf7 小时前
工业级部署指南:在西门子IOT2050(Debian 12)上搭建.NET 9.0环境与应用部署
物联网·.netcore·智能制造·边缘网关·西门子·iot 2050
睡前要喝豆奶粉8 小时前
在.NET Core Web Api中使用JWT并配置UserContext获取用户信息
前端·.netcore
睡前要喝豆奶粉8 小时前
在.NET Core Web Api中使用阿里云OSS
阿里云·c#·.netcore
周杰伦fans17 小时前
.NET Core WebAPI 中 HTTP 请求方法详解:从新手到精通
网络协议·http·.netcore
睡前要喝豆奶粉3 天前
.NET Core Web API开发需引入的三个基本依赖配置说明
oracle·c#·.netcore
_pass_3 天前
flask 框架的ORM 学习及应用
学习·flask·orm
睡前要喝豆奶粉3 天前
.NET Core Web API中数据库相关配置
数据库·c#·.netcore
Archy_Wang_13 天前
Hangfire 入门与实战:在 .NET Core 中实现可靠后台任务处理
c#·.netcore
睡前要喝豆奶粉4 天前
在.NET Core Web Api中使用redis
redis·c#·.netcore
睡前要喝豆奶粉5 天前
多表分页联查——EF Core方式和Dapper方式
c#·.netcore