十年河東,十年河西,莫欺少年窮
學無止境,精益求精
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
項目文件如下:
<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 用於存放數據庫實體相關的類,內有一個學生類
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 用於存放數據庫實體相關配置,用於設定字段長度,字段備註,表主鍵、外鍵等
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); } } }
MyDbContext.cs 爲數據庫上下文,用於數據庫相關配置
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
項目文件如下:
<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、簡單測試
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運行結果
數據庫刷新後
@陳大六的博客