Net6 CodeFirst注入MySQL数据库上下文及mock测试数据
十年河东,十年河西,莫欺少年穷
学无止境,精益求精
2022太难了,好多公司倒闭,互联网不景气,工作难找,苏州的C#/Net程序员的招聘更是少之又少,java,C,等其他语言也是供大于求,总之,难上加难!唯有珍惜现有工作方为上策,真心希望经济好转
1、先建DbContext层
使用VS2022新建一个webApi项目,然后添加一个类库,名称为:WebMysqlDbContext
对此类库添加Nuget引用,如下
Microsoft.EntityFrameworkCore.Design 6.0.8 Microsoft.EntityFrameworkCore.Relational 6.0.8 Microsoft.EntityFrameworkCore.Tools 6.0.8 Pomelo.EntityFrameworkCore.MySql 6.0.2
项目文件如下:
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
<Project Sdk="Microsoft.NET.Sdk"> <PropertyGroup> <TargetFramework>net6.0</TargetFramework> <ImplicitUsings>enable</ImplicitUsings> <Nullable>enable</Nullable> </PropertyGroup> <ItemGroup> <PackageReference Include="Microsoft.EntityFrameworkCore.Design" Version="6.0.8"> <PrivateAssets>all</PrivateAssets> <IncludeAssets>runtime; build; native; contentfiles; analyzers; buildtransitive</IncludeAssets> </PackageReference> <PackageReference Include="Microsoft.EntityFrameworkCore.Relational" Version="6.0.8" /> <PackageReference Include="Microsoft.EntityFrameworkCore.Tools" Version="6.0.8"> <PrivateAssets>all</PrivateAssets> <IncludeAssets>runtime; build; native; contentfiles; analyzers; buildtransitive</IncludeAssets> </PackageReference> <PackageReference Include="Pomelo.EntityFrameworkCore.MySql" Version="6.0.2" /> </ItemGroup> </Project>
DbDtos 用于存放数据库实体相关的类,内有一个学生类
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
namespace WebMysqlDbContext.DbDtos { public class T_Student { public string? uid { get; set; } public string? studentName { get; set; } public string? studentNo { get; set; } public StudentSexEnum sex { get; set; } public string? telephone { get; set; } public bool isEnable { get; set; } = true; public DateTime createTime { get; set; } } public enum StudentSexEnum { 男, 女 } }
DbConfigs 用于存放数据库实体相关配置,用于设定字段长度,字段备注,表主键、外键等
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
using Microsoft.EntityFrameworkCore; using Microsoft.EntityFrameworkCore.Metadata.Builders; using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using WebMysqlDbContext.DbDtos; namespace WebMysqlDbContext.DbConfigs { internal class T_StudentConfig : IEntityTypeConfiguration<T_Student> { public void Configure(EntityTypeBuilder<T_Student> builder) { builder.ToTable("T_Students"); builder.HasKey(A => A.uid); builder.Property(A => A.uid).HasColumnType("varchar(64)").HasComment("主键"); builder.Property(A => A.studentName).HasColumnType("nvarchar(64)").HasComment("学生姓名"); builder.Property(A => A.studentNo).HasColumnType("varchar(16)").HasComment("学号"); builder.Property(A => A.telephone).HasColumnType("varchar(20)").HasComment("联系方式"); //全局过滤器 builder.HasQueryFilter(A => A.isEnable == true); } } }
除了上述外,在此再补充一个生成测试数据的方法:
//mock一条数据 builder.HasData(new T_Student() { });
MyDbContext.cs 为数据库上下文,用于数据库相关配置
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
using Microsoft.EntityFrameworkCore; using Microsoft.EntityFrameworkCore.Design; using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using WebMysqlDbContext.DbDtos; namespace WebMysqlDbContext { public class MyDbContext : DbContext { public DbSet<T_Student> Students { get; set; } public MyDbContext() : base() { } public MyDbContext(DbContextOptions<MyDbContext> options) : base(options) { } protected override void OnModelCreating(ModelBuilder modelBuilder) { //关闭级联删除 var foreignKeys = modelBuilder.Model.GetEntityTypes().SelectMany(e => e.GetForeignKeys()).Where(fk => fk.DeleteBehavior == DeleteBehavior.Cascade); foreach (var fk in foreignKeys) { fk.DeleteBehavior = DeleteBehavior.Restrict; } base.OnModelCreating(modelBuilder); //从当前程序集命名空间加载所有的IEntityTypeConfiguration modelBuilder.ApplyConfigurationsFromAssembly(this.GetType().Assembly); } } /// <summary> /// 开发环境专用 用于add-Migration 时使用 /// </summary> public class MyDbContextFactory : IDesignTimeDbContextFactory<MyDbContext> { public MyDbContext CreateDbContext(string[] args) { var optionsBuilder = new DbContextOptionsBuilder<MyDbContext>(); optionsBuilder.UseMySql<MyDbContext>("Server=localhost;Port=3306;Database=Student;Uid=root;Pwd=chen1234;", ServerVersion.AutoDetect("Server=localhost;Port=3306;Database=Student;Uid=root;Pwd=123456;")); return new MyDbContext(optionsBuilder.Options); } } }
2、webApi层相关操作
在webApi层引入如下Nuget包
Microsoft.EntityFrameworkCore.Design 6.0.8 Pomelo.EntityFrameworkCore.MySql 6.0.2
项目文件如下:
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
<Project Sdk="Microsoft.NET.Sdk.Web"> <PropertyGroup> <TargetFramework>net6.0</TargetFramework> <Nullable>enable</Nullable> <ImplicitUsings>enable</ImplicitUsings> <UserSecretsId>243f8ed9-608e-4fd3-95b5-6a55d59118f4</UserSecretsId> <DockerDefaultTargetOS>Linux</DockerDefaultTargetOS> </PropertyGroup> <ItemGroup> <PackageReference Include="Microsoft.EntityFrameworkCore.Design" Version="6.0.8"> <PrivateAssets>all</PrivateAssets> <IncludeAssets>runtime; build; native; contentfiles; analyzers; buildtransitive</IncludeAssets> </PackageReference> <PackageReference Include="Microsoft.VisualStudio.Azure.Containers.Tools.Targets" Version="1.15.1" /> <PackageReference Include="Swashbuckle.AspNetCore" Version="6.2.3" /> <PackageReference Include="Pomelo.EntityFrameworkCore.MySql" Version="6.0.2" /> </ItemGroup> <ItemGroup> <ProjectReference Include="..\WebMysqlDbContext\WebMysqlDbContext.csproj" /> </ItemGroup> </Project>
在Program.cs中注入数据库上下文
builder.Services.AddDbContext<MyDbContext>(options => options.UseMySql(builder.Configuration.GetConnectionString("studentDbContext"), ServerVersion.AutoDetect(builder.Configuration.GetConnectionString("studentDbContext"))));
配置文件如下:
{ "Logging": { "LogLevel": { "Default": "Information", "Microsoft.AspNetCore": "Warning" } }, "AllowedHosts": "*", "ConnectionStrings": { "studentDbContext": "Server=localhost;Port=3306;Database=Student;Uid=root;Pwd=123456;" } }
在程序包管理控制台中初始化数据库
输入
add-migration initdb
update-database
3、去数据库中查看生成的数据库及数据表
4、简单测试
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
using Microsoft.AspNetCore.Mvc; using WebMysqlDbContext; using WebMysqlDbContext.DbDtos; namespace WebMySql.Controllers { [ApiController] [Route("[controller]")] public class WeatherForecastController : ControllerBase { private readonly ILogger<WeatherForecastController> _logger; private readonly MyDbContext context; public WeatherForecastController(ILogger<WeatherForecastController> logger, MyDbContext context) { _logger = logger; this.context = context; } [HttpGet(Name = "GetWeatherForecast")] public IActionResult Get() { T_Student student = new T_Student() { createTime = DateTime.Now, isEnable = true, sex = StudentSexEnum.女, studentName = "陈红", studentNo = "081309207", telephone = "18137070152", uid = Guid.NewGuid().ToString() }; context.Students.Add(student); context.SaveChanges(); var result = context.Students.ToList(); return Ok(result); } } }
swagger运行结果
数据库刷新后
@陈大六的博客