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

相关推荐
lixww.cn1 天前
ASP.NET Core与配置系统的集成
.netcore
张3蜂3 天前
如何利用Docker和.NET Core实现环境一致性、简化依赖管理、快速部署与扩展,同时提高资源利用率、确保安全性和生态系统支持
docker·容器·.netcore
lixww.cn3 天前
.NET Core 中依赖注入的使用
.netcore
醉の虾4 天前
Vue3 结合 .NetCore WebApi 前后端分离跨域请求简易实例
前端·vue.js·.netcore
时光追逐者4 天前
一组开源、免费、Metro风格的 WPF UI 控件库
ui·开源·c#·.net·wpf·.netcore·微软技术
时光追逐者5 天前
C#/.NET/.NET Core技术前沿周刊 | 第 23 期(2025年1.20-1.26)
microsoft·c#·.net·.netcore·微软技术
lixww.cn5 天前
.NET Core缓存
缓存·.netcore
lixww.cn6 天前
ASP.NET Core MVC
c#·mvc·.netcore
亦世凡华、6 天前
从CRUD到高级功能:EF Core在.NET Core中全面应用(四)
经验分享·.netcore·ef core·表达式树
lixww.cn6 天前
ASP.NET Core WebAPI的异步及返回值
.netcore