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

相关推荐
全栈小53 天前
【C#】.net core,静态方法线程安全解析,面试时经常被问的线程安全就藏在里面
安全·c#·.netcore
触底反弹3 天前
🚀 Next.js 全栈项目数据库连接实战:Drizzle ORM + Supabase 从零到跑通
postgresql·orm·next.js
姚杨3 天前
聊了三年 DDD,代码里全是贫血模型:老陈一句话点破,落地先过这几关
后端·orm
Darling噜啦啦4 天前
从零搭建单词管理系统:Next.js + Supabase + Drizzle ORM 全栈实战
数据库·orm·next.js
不好听6134 天前
ORM:让你不用再手写SQL语句
orm
柒和远方4 天前
V077:Next.js 后台的认证与权限防线:首个超级管理员的事务锁初始化、会话令牌哈希,与四道管理员保护规则
orm·next.js
清风与日月5 天前
Yitter.IdGenerator:高性能分布式唯一ID生成器详解
分布式·c#·.net·.netcore
__zRainy__6 天前
Node系列 · ORM:mysql 驱动程序
数据库·后端·mysql·node.js·orm
CSharp精选营7 天前
用 .NET 8 + uni-app 做一套多租户畜牧 SaaS:我们在秦巴牧云踩过的 6 个坑
uni-app·efcore·.net8·多租户·saas踩坑
Lost of 程序猿8 天前
ASP.NET Core 后台任务全景:从 BackgroundService 到 Channel 队列,再到分布式调度
后端·asp.net·.netcore