• 使用CodeFirst连接Mysql


    之前写过连接Sqlite的示例。使用Code First_故里2130的博客-CSDN博客_codefirst

    这里依然使用ORM中的EntityFrameworkCore框架,ORM就是对象关系映射,用于实现面向对象编程语言里不同类型系统的数据之间的转换,也就是说,当我们的数据库改变了,可以很快速的进行切换,核心就是代码先行的。其实ORM分为很多种类,包括:

    EF(Entity Framework),随着core的出现,也就是有了EFC(EntityFrameworkCore),SqlSugar,Dapper等等框架。

    1.使用vs2022建立一个.net core web api项目

    2.在nuget中搜索EntityFrameworkCore.MySql,进行安装,当我们用的是mysql,那么这里就选择mysql,当换数据库的时候,这里可以修改成别的数据库。

    (注意版本问题,下面有坑)

    3.再安装Microsoft.EntityFrameworkCore.Tools,主要是操作数据库的

     4. 至此,我们需要安装的包就完成了,开始写代码

    5. 建立一个user类,并且增加主键,这里可能有很多的类,依次建立即可

    1. using System;
    2. using System.Collections.Generic;
    3. using System.ComponentModel;
    4. using System.ComponentModel.DataAnnotations;
    5. using Microsoft.EntityFrameworkCore;
    6. using System.ComponentModel.DataAnnotations.Schema;
    7. using System.Linq;
    8. using System.Threading.Tasks;
    9. namespace mysqlCodeFirst
    10. {
    11. ///
    12. /// 用户表
    13. ///
    14. public class User
    15. {
    16. ///
    17. /// id
    18. ///
    19. [Key] //主键
    20. [MaxLength(10), MinLength(5)] //长度,最大10,最小5
    21. public int Id { get; set; }
    22. ///
    23. /// 姓名
    24. ///
    25. public string Name { get; set; }
    26. ///
    27. /// 年龄
    28. ///
    29. public int age { get; set; }
    30. }
    31. }

    6.建立EFmysqlContext类,并且继承DbContext,手动初始化。这里就是上面建立类的一个汇总,类和类之间有关系,都要在这里进行体现,一个类就是一个表,也就是数据库中表和表的关系,1对1,1对多,多对多的关系,注释等等全部在这里体现。关系要写OnModelCreating方法中

    1. using Microsoft.EntityFrameworkCore;
    2. using System;
    3. using System.Collections.Generic;
    4. using System.Linq;
    5. using System.Threading.Tasks;
    6. namespace mysqlCodeFirst
    7. {
    8. public class EFmysqlContext : DbContext
    9. {
    10. public EFmysqlContext(DbContextOptions options) : base(options)
    11. {
    12. }
    13. protected override void OnModelCreating(ModelBuilder modelBuilder)
    14. {
    15. //这里写表(类)与表(类)之间1对1,1对多,多对多的关系
    16. }
    17. public DbSet Users { get; set; } //这里有几个类就写几个类
    18. }
    19. }

    7.在appsettings.json文件中进行配置数据库字符串,appsettings.json在core中就是配置文件,类似于app.config和web.config的作用。

    1. {
    2. "Logging": {
    3. "LogLevel": {
    4. "Default": "Information",
    5. "Microsoft": "Warning",
    6. "Microsoft.Hosting.Lifetime": "Information"
    7. }
    8. },
    9. "AllowedHosts": "*",
    10. "ConnectionSetting": {
    11. "MySqlConnection": "Data Source=localhost;User ID=root;Password=123456;Database=mysqlCodeFirst;Allow User Variables=True;Charset=utf8;"
    12. }
    13. }

    8.在Startup.cs进行注入,这里注入的是MySQL数据库,可以修改成别的数据库,也就是前面说的,更改数据库很方便

    1. services.AddDbContext(options =>
    2. {
    3. options.UseMySQL(Configuration["ConnectionSetting:MySqlConnection"]);
    4. //这里可以修改别的数据库
    5. });

    9. 现在开始迁入数据库中,在程序包管理器控制台中,输入Add-Migration xxx,xxx是迁移的名字。

    注意:这里如果选择的包和mysql的版本不一样,可能会报错,报错就百度吧。本人选择的就不一样,导致报错问题,最后换了一下包的版本就可以了,所以在使用的时候,最好都使用最新版。

    可见成功了,右侧有文件生成

    10.再输入Update-Database,创建数据库完成

    11.我们打开MySQL数据库,可以看到数据库和表

    12. 接下来,我们进行使用

    需要先进行注入

     把代码写进控制类中

    1. using Microsoft.AspNetCore.Mvc;
    2. using Microsoft.Extensions.Logging;
    3. using System;
    4. using System.Collections.Generic;
    5. using System.Linq;
    6. using System.Threading.Tasks;
    7. namespace mysqlCodeFirst.Controllers
    8. {
    9. [ApiController]
    10. [Route("[controller]")]
    11. public class WeatherForecastController : ControllerBase
    12. {
    13. private static readonly string[] Summaries = new[]
    14. {
    15. "Freezing", "Bracing", "Chilly", "Cool", "Mild", "Warm", "Balmy", "Hot", "Sweltering", "Scorching"
    16. };
    17. private readonly ILogger _logger;
    18. private readonly EFmysqlContext context;
    19. public WeatherForecastController(ILogger logger, EFmysqlContext context)
    20. {
    21. _logger = logger;
    22. this.context = context;
    23. }
    24. [HttpGet]
    25. public IEnumerable Get()
    26. {
    27. User user = new User();
    28. user.age = 15;
    29. user.Id = 1;
    30. user.Name = "张三";
    31. context.Add(user);
    32. context.SaveChanges();
    33. var rng = new Random();
    34. return Enumerable.Range(1, 5).Select(index => new WeatherForecast
    35. {
    36. Date = DateTime.Now.AddDays(index),
    37. TemperatureC = rng.Next(-20, 55),
    38. Summary = Summaries[rng.Next(Summaries.Length)]
    39. })
    40. .ToArray();
    41. }
    42. }
    43. }

    13.打开MySQL数据库,就能看到已经插入成功了。

     官网说明

    DbContext 生存期、配置和初始化 - EF Core | Microsoft Docs

  • 相关阅读:
    C++ Reference: Standard C++ Library reference: C Library: cmath: asin
    【贪心算法-LeetCode3:无重复字符的最长子串(Java实现)】
    自适应模糊神经网络与bp神经网络的区别
    用C#也能做机器学习?
    写年度总结报告的注意事项
    针对千万级人口城市的核酸检测系统的设计分享
    AR人体姿态识别,实现无边界的人机交互
    【计算机毕业设计】50.课程设计管理系统
    【Langchain Agent研究】SalesGPT项目介绍(四)
    debug的操作
  • 原文地址:https://blog.csdn.net/u012563853/article/details/126465062