9.2 Entity Framework Core
概述
Entity Framework Core (EF Core) 是微软推出的轻量级、可扩展、开源的对象关系映射(ORM)框架,是.NET平台中数据库访问的核心技术之一。它允许开发者以面向对象的方式操作数据库,无需编写大量SQL语句。
核心概念
1. DbContext
DbContext是EF Core的核心类,代表与数据库的会话,用于:
- 管理数据库连接
- 配置模型与数据库映射
- 执行数据查询和保存
- 跟踪实体状态变化
public class AppDbContext : DbContext
{
public DbSet<Product> Products { get; set; }
public DbSet<Category> Categories { get; set; }
protected override void OnConfiguring(DbContextOptionsBuilder options)
=> options.UseSqlServer("YourConnectionString");
}
2. 实体类
POCO(Plain Old CLR Object)类,映射数据库表:
public class Product
{
public int Id { get; set; }
public string Name { get; set; }
public decimal Price { get; set; }
// 导航属性
public Category Category { get; set; }
}
主要功能
1. 数据库迁移
EF Core使用迁移系统管理数据库架构变更:
# 常用命令
dotnet ef migrations add InitialCreate
dotnet ef database update
2. 数据操作
查询数据
// LINQ查询
var cheapProducts = dbContext.Products
.Where(p => p.Price < 100)
.ToList();
添加数据
var newProduct = new Product { Name = "Laptop", Price = 999.99m };
dbContext.Products.Add(newProduct);
dbContext.SaveChanges();
更新数据
var product = dbContext.Products.Find(1);
product.Price = 899.99m;
dbContext.SaveChanges();
删除数据
var product = dbContext.Products.Find(1);
dbContext.Products.Remove(product);
dbContext.SaveChanges();
3. 关系映射
EF Core支持多种关系类型:
- 一对一
- 一对多
- 多对多
// 一对多示例
public class Category
{
public int Id { get; set; }
public string Name { get; set; }
public ICollection<Product> Products { get; set; }
}
高级特性
1. 延迟加载
// 需要安装Microsoft.EntityFrameworkCore.Proxies
services.AddDbContext<AppDbContext>(options =>
options.UseLazyLoadingProxies()
.UseSqlServer(connectionString));
2. 预加载(Eager Loading)
var products = dbContext.Products
.Include(p => p.Category)
.ToList();
3. 显式加载
var product = dbContext.Products.Find(1);
dbContext.Entry(product)
.Reference(p => p.Category)
.Load();
4. 原始SQL查询
var products = dbContext.Products
.FromSqlRaw("SELECT * FROM Products WHERE Price > {0}", 100)
.ToList();
性能优化
- 批量操作:使用
AddRange/RemoveRange减少数据库往返 - AsNoTracking:查询只读数据时提高性能
- DbContext池:在ASP.NET Core中复用DbContext实例
- 编译查询:重复查询使用
EF.CompileQuery
实际应用建议
- 仓储模式:抽象数据访问层
- 工作单元模式:管理事务
- DTO映射:使用AutoMapper等工具
- 日志记录:监控生成的SQL
// 配置日志示例
options.UseSqlServer(connectionString)
.LogTo(Console.WriteLine, LogLevel.Information);
常见问题解决
- 并发冲突:使用并发令牌(
[ConcurrencyCheck]) - 连接泄露:确保DbContext正确释放
- N+1查询问题:合理使用Include
- 迁移冲突:团队协作时注意迁移文件同步
学习资源
- 官方文档:https://docs.microsoft.com/ef/core/
- GitHub仓库:https://github.com/dotnet/efcore
- EF Core Power Tools:可视化工具扩展
- 社区博客:如Microsoft DevBlogs中的EF Core相关内容
通过掌握EF Core,开发者可以显著提高数据访问层的开发效率,同时保持代码的整洁性和可维护性。
