欢迎来到尧图网

客户服务 关于我们

您的位置:首页 > 教育 > 幼教 > efCore+Mysql8,使用及表的迁移

efCore+Mysql8,使用及表的迁移

2024/10/25 12:23:12 来源:https://blog.csdn.net/m0_46319477/article/details/141142351  浏览:    关键词:efCore+Mysql8,使用及表的迁移

1.安装 Nuget 包

Microsoft.EntityFrameworkCore > Microsoft.EntityFrameworkCore.Tools > Pomelo.EntityFrameworkCore.MySql

2.MVC 框架搭出来

models

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


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 类

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 中配置连接字段

"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

版权声明:

本网仅为发布的内容提供存储空间,不对发表、转载的内容提供任何形式的保证。凡本网注明“来源:XXX网络”的作品,均转载自其它媒体,著作权归作者所有,商业转载请联系作者获得授权,非商业转载请注明出处。

我们尊重并感谢每一位作者,均已注明文章来源和作者。如因作品内容、版权或其它问题,请及时与我们联系,联系邮箱:809451989@qq.com,投稿邮箱:809451989@qq.com