ccruiの博客

ccruiの博客

如何使用.Net7连接MySQL

80
2023-03-06

测试完成

新建项目

引用NuGet包

使用NuGet引用以下包:

Microsoft.EntityFrameworkCore
Microsoft.EntityFrameworkCore.Tools
//根据数据库进行选择
Pomelo.EntityFrameworkCore.MySql(连接Mysql)
Microsoft.EntityFrameworkCore.SqlServer(连接SqlServer)
Oracle.EntityFrameworkCore(连接Oracle)Ï

创建数据类实体类

using System.ComponentModel.DataAnnotations;
using System.ComponentModel.DataAnnotations.Schema;

namespace Test01.Entity;

public class TestEntity
{
    public TestEntity(int id, string name, int age)
    {
        Id = id;
        Name = name;
        Age = age;
    }

    [Key] [Column("id")] public int Id { get; set; }
    [Column("name")] public string Name { get; set; }
    [Column("age")] public int Age { get; set; }
}

创建数据库连接类

using Microsoft.EntityFrameworkCore;
using Test01.Entity;

namespace Test01.Context;

public class TestContext : DbContext
{
    public TestContext()
    {
    }

    public TestContext(DbContextOptions<TestContext> options) : base(options)
    {
    }

    // 定义表
    public DbSet<TestEntity> test { get; set; }
}

向项目中注入数据库连接

Program.cs文件中添加:

// 在服务容器中添加 TestContext 类别作为数据库内容服务
builder.Services.AddDbContext<TestContext>(opt =>
{
    // 从 appsettings.json 文件中取得 MySQL 的连接字符串
    string? connectionString = builder.Configuration.GetConnectionString("MySQL");
    // 自动侦测 MySQL 的服务器版本
    var serverVersion = ServerVersion.AutoDetect(connectionString);
    // 使用 MySQL 数据库提供者和连接字符串来配置数据库内容选项
    opt.UseMySql(connectionString, serverVersion);
});

向配置文件中写入Mysql信息

appsettings.json文件中添加:

  "ConnectionStrings": {
    "MySQL":"server=[YourIP];user id=[UserName];password=[123456];port=[3306];database=[testdb]"
  }

请酌情修改[]中的内容

测试

using Microsoft.AspNetCore.Mvc;
using Test01.Context;
using Test01.Entity;

namespace Test01.Controllers;

[ApiController]
[Route("[controller]")]
public class TestController : ControllerBase
{
    private readonly TestContext _testContext;

    public TestController(TestContext testContext)
    {
        _testContext = testContext;
    }

    [HttpGet(Name = "GetTest")]
    public List<TestEntity> GetTest(int id)
    {
        return _testContext.test
            .Where(o => o.Id == id)
            .ToList();
    }
}