EF Core 与 MySQL:介绍与入门实操


简介

EF Core(Entity Framework Core)是Microsoft推出的开源跨平台ORM框架,支持SQL Server、SQLite、MySQL、PostgreSQL等主流数据库,并提供向NoSQL数据库(如Cosmos DB)的扩展能力。它通过DbContext管理实体与数据库的映射关系,提供LINQ查询、CRUD操作及数据库迁移功能,适用于微服务架构、Web API开发等场景。

核心架构与功能

  • DbContext‌:作为EF Core的核心类,管理数据库连接和实体对象映射,所有CRUD操作均通过其实现。典型用法包括继承DbContext并配置DbSet属性来映射数据库表。
  • 数据库支持‌:兼容SQL Server、MySQL、PostgreSQL、SQLite等主流数据库,通过NuGet包集成不同提供程序(如Microsoft.EntityFrameworkCore.SqlServer)。
  • LINQ查询‌:允许开发者使用面向对象的方式编写查询,减少直接SQL编写需求。

性能优化

  • DbContext池化‌:通过AddDbContextPool复用上下文实例,减少高频创建开销,适用于高性能场景。
  • 异步操作‌:支持异步方法如SaveChangesAsync,提升应用响应能力。

开发流程

  • 模型定义‌:通过实体类映射数据库表结构,例如Blog和Post类的一对多关系。
  • 迁移与架构管理‌:使用命令行工具生成迁移脚本,同步数据库结构变更。
  • 依赖注入集成‌:在ASP.NET Core中通过AddDbContext注册服务,实现控制器自动注入。

版本与兼容性

  • 当前稳定版本为EF Core 9.0(支持至2026年5月),目标框架为.NET 8,提供跨平台兼容性(Windows/Linux/macOS)。历史版本如EF Core 5.0基于.NET Standard 2.1,已停止支持。

应用场景

  • 微服务架构‌:管理各服务的私有数据库。
  • Web API开发‌:与ASP.NET Core深度集成,快速构建数据驱动接口。

入门实操

在本文中,将使用 Entity Framework Core 8.0 对 MySQL 5.7.2 数据库执行数据访问。

1、安装依赖

确保已安装.NET SDK(推荐8.0)和MySQL数据库。通过NuGet包管理器或者以下命令添加NuGet包:

--包
Microsoft.EntityFrameworkCore
Pomelo.EntityFrameworkCore.MySql
Microsoft.EntityFrameworkCore.Tools
--命令
dotnet add package Microsoft.EntityFrameworkCore
dotnet add package Pomelo.EntityFrameworkCore.MySql
dotnet add package Microsoft.EntityFrameworkCore.Tools

注意:版本的选择尽量与.NET版本一致,我这里使用的.NET8.0。

2、连接字符串配置

在appsettings.json中配置MySQL连接信息:

{ "ConnectionStrings": { "DefaultConnection": "server=localhost;port=3306;database=testdb;user=root;password=yourpassword;" } }
//或直接在DbContext中配置:
optionsBuilder.UseMySql(connectionString, ServerVersion.AutoDetect(connectionString));

3、创建实体模型

定义与数据库表对应的实体类,例如:

namespace CP.ProductService.Domains.Models
{
    /// <summary>
    /// 商品 聚合根
    /// </summary>
    public class Product
    {
        public int Id { get; set; } 

        public string Name { get; set; }    

        public decimal Price { get; set; }

        public string Description { get; set; }

        public List<ProductImage> ProductImages { get; set; }
    }
}
namespace CP.ProductService.Domains.Models
{
    /// <summary>
    /// 商品图片 【实体】
    /// </summary>
    public class ProductImage
    {
        public int Id { get; set; } 

        public string Name { get; set; }    

        public string Path { get; set; }

        public string Description { get; set; }
    }
}

4、配置DbContext上下文

创建上下文类并映射实体集:

using CP.ProductService.Domains.Models;
using Microsoft.EntityFrameworkCore;

namespace CP.ProductService.Infrastructures.Datas
{
    /// <summary>
    /// 创建上下文
    /// </summary>
    public class ProductContext : DbContext
    {
        public ProductContext(DbContextOptions options) : base(options)
        {
        }

       // protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
       //=> optionsBuilder.UseMySql("Serve=localhost;Port=3306;DataBase=ProductService;Uid=root;Pwd=123456;"
       //    , new MySqlServerVersion("5.7.29"));

        public DbSet<Product> Products { get; set; }    
    }
}

5、依赖注入

在program.cs中注入UserContext依赖:

//1、注册ProductContext
builder.Services.AddDbContext<ProductContext>(option => {
    //2、使用MySql
    option.UseMySql(builder.Configuration.GetConnectionString("Default"), 
        new MySqlServerVersion("5.7.29"));
});

6、使用迁移来创建数据库

    • 验证是否已正确安装 EF Core CLI 工具:
      dotnet ef 是 Entity Framework Core 提供的命令行工具,用于执行数据库迁移、模型代码生成等设计时任务。
      dotnet ef

如上图所示,看到这个符号就是已安装成功。

注意:如果工具未安装就运行”dotnet ef“,会报”无法执行,因为找不到指定的命令或文件。可能造成此问题的原因包括:*内置 dotnet 命令拼写错误。*你打算执行 .NET 程序,但 dotnet-ef 不存在。*你打算运行全局工具,但在 PATH 上找不到具有此名称且带有 dotnet 前缀的可执行文件。“的错误,如下图。

    • 安装工具dotnet ef
//安装最新版
dotnet tool install --global dotnet-ef
//安装指定版本(避免兼容性问题)
dotnet tool install --global dotnet-ef --version 8.0

//顺便记录下卸载命令
dotnet tool uninstall --global dotnet-ef

    • 初始化迁移‌(使用的是 Code First 迁移)

migrations 命令为迁移搭建基架,为模型创建初始表集。

dotnet ef migrations add InitialCreate

 可以看到迁移类文件已生成。

    • 更新数据库架构‌

database update 命令将创建数据库,并将新的迁移应用到该数据库。

dotnet ef database update

 可以看到数据库和表都生成了。

    • ‌更新迁移‌和数据库架构
      数据库和表结构有变化时,需要更新迁移,更新时必须新定义一个迁移类名,如下依次执行命令。
      dotnet ef migrations add InitialCreate_xxx
      dotnet ef database update

      改一下ProductImage实体类的字段,Path改为Url,依次执行以上两个命令,会生成增量迁移类文件,数据库里ProductImage表字段也会更新,效果如下图。

      注意:如果迁移类名用已存在的迁移类名,会报”The name ‘xxxxx’ is used by an existing migration.“的错误,如下图。

       

7、基本增删查改操作

    • 直接上示例代码
      // 添加数据
      using (var context = new ProductContext())
      {
          var product = new Product{ 
              Name = "Laptop", 
              Price = 999.99m, 
              Description= "笔记本"
          };
          context.Products.Add(product);
          
          context.SaveChanges();
      }
      
      // 查询数据
      using (var context = new ProductContext())
      {
          var expensiveProducts = context.Products
              .Where(p => p.Price > 500)
              .OrderByDescending(p => p.Price)
              .ToList();
      }
      
      // 更新数据
      using (var context = new ProductContext())
      {
          var product = context.Products.FirstOrDefault(p => p.Name == "Laptop");
          if (product != null)
          {
              product.Price = 899.99m;
              context.SaveChanges();
          }
      }
      
      // 删除数据
      using (var context = new ProductContext())
      {
          var product = context.Products.FirstOrDefault(p => p.Name == "Laptop");
          if (product != null)
          {
              context.Products.Remove(product);
              context.SaveChanges();
          }
      }

总结

本章到到此结束,本文主要介绍了EF Core的理论部分,如何使用EF Core连接MySQL执行数据访问,包括模型创建、DbContext配置、数据库迁移以及基本的增删改查操作。