Entity-Framework-Core迁移与优化
Entity Framework Core迁移与性能优化详解。
1. 迁移命令
dotnet ef migrations add InitialCreate
dotnet ef database update
dotnet ef migrations remove # 撤销上次迁移
2. 常见优化
2.1 N+1 问题
// N+1 查询
var blogs = context.Blogs.ToList();
foreach (var blog in blogs) {
var posts = blog.Posts.ToList(); // 每个博客一次查询
}
// Eager Loading
var blogs = context.Blogs.Include(b => b.Posts).ToList();
2.2 选择性加载
// 只查询需要的列
var results = context.Users
.Where(u => u.Active)
.Select(u => new { u.Id, u.Name })
.ToList();
2.3 批量操作
// 使用 EFCore.BulkExtensions
context.BulkInsert(entities);
context.BulkUpdate(entities);
2.4 分割查询
context.Blogs
.Include(b => b.Posts)
.AsSplitQuery() // 拆分为多个 SQL 查询
.ToList();