首页 > 数据库 >Net6 CodeFirst注入MySQL数据库上下文

Net6 CodeFirst注入MySQL数据库上下文

时间:2022-11-28 14:35:08浏览次数:50  
标签:CodeFirst builder MySQL System Microsoft EntityFrameworkCore using Net6 public

十年河东,十年河西,莫欺少年穷

学无止境,精益求精 

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>
View Code

 

 

 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
    {
        男,
        女
    }
}
View Code

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);
        }
    }
}
View Code

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);
        }
    }
} 
View Code

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>
View Code

在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);
        }
    }
}
View Code

swagger运行结果

数据库刷新后

 

 @陈大六的博客

标签:CodeFirst,builder,MySQL,System,Microsoft,EntityFrameworkCore,using,Net6,public
From: https://www.cnblogs.com/chenwolong/p/16932097.html

相关文章

  • mysql,在win10上绿色安装5.7版本
    1.下载地址,选择5.7的zip包https://downloads.mysql.com/archives/community/2.解压到自定义路径下我这里选择的路径D:\mysql手动创建了文件my.inimy.ini内容点击查......
  • Mysql与Redis如何保证数据的一致性?
    问题分析:当MySQL中的数据发生更新时,就面临一个问题,如何确保MySQL与Redis数据的一致性,我们有两个选择:先更新MySQL,后删除(或更新)Redis先删除(或更新)Redis,后更新MySQL......
  • python3.7安装mysqlclient失败问题
    问题直接使用pipinstall安装mysqlclient最新版本2.1.1失败了,提示“Failedbuildingwheelformysqlclient”解决步骤:换wheel方式安装,去pypi官网准备下载文件,突然发......
  • ThinkPHP6 使用原生mysql表达式
    1if(!empty($param)){2$where[]=['','exp',Db::raw("FIND_IN_SET(".$param.",mysqlfield)")];3}使用这种查询表达式,注意几点:1.数组......
  • JavaWeb-MySql高级
    JavaWeb-MySql高级1,约束1.1概念约束是作用于表中列上的规则,用于限制加入表的数据例如:我们可以给id列加约束,让其值不能重复,不能为null值。约束的存在保证了数据......
  • MySQL锁:InnoDB行锁需要避免的坑
    前言换了工作之后,接近半年没有发博客了(一直加班),emmmm.....今天好不容易有时间,记录下工作中遇到的一些问题,接下来应该重拾知识点了。因为新公司工作中MySQL库经常出现......
  • mysql删除所有表中数据
    建立存储过程dropprocedureifexistsdel_all_tb;delimiter$$createproceduredel_all_tb(dbchar(20))begindeclaredoneintdefault0;declaretbc......
  • mysql只更改字段年月日时间,时分秒不变
    数据库导入数据,年月日出现问题了,如图所示,只能通过sql更改年月日。想修改一列时间,将其年月日修改为自己想要的时间执行如下sql:UPDATEyieldsetdataTime=ADDTIME(DAT......
  • Mysql 直接拷贝数据库文件导致表不显示的问题
    前言:最近有一个需求,需要迁移数据库中的其中一个库,需要迁移的那个数据库占用了700多G的空间,所以采用直接拷贝数据库文件的方式,拷贝到另一台服务器后发现表不显示,记录本次问......
  • mysql 数据库管理
    一、常用的数据类型二、数据库管理2.1创建数据库和表-create2.2删除数据库和表-drop  一、常用的数据类型类型解释举例int整型......