Z
ZHANK
编程在线教程C# 教程Entity Framework Core
Web 开发

Entity Framework Core

EF Core 模型定义、DbContext、迁移 Migration、LINQ 查询

Entity Framework Core

EF Core 是 .NET 的 ORM 框架——用 C# 对象操作数据库,LINQ 自动翻译成 SQL。

学完本章你将: 掌握模型定义、DbContext、Migration 迁移、LINQ 查询。


模型与 DbContext

csharp
public class Blog
{
    public int Id { get; set; }
    public string Title { get; set; } = "";
    public List<Post> Posts { get; set; } = new();
}

public class Post
{
    public int Id { get; set; }
    public string Content { get; set; } = "";
    public int BlogId { get; set; }
    public Blog Blog { get; set; } = null!;
}

public class AppDbContext : DbContext
{
    public DbSet<Blog> Blogs => Set<Blog>();
    public DbSet<Post> Posts => Set<Post>();

    protected override void OnConfiguring(DbContextOptionsBuilder options)
        => options.UseSqlite("Data Source=app.db");
}

LINQ 查询

csharp
// 查所有
var blogs = await db.Blogs.ToListAsync();

// 条件 + 排序
var recent = await db.Posts
    .Where(p => p.Blog.Title.Contains("C#"))
    .OrderByDescending(p => p.Id)
    .Take(10)
    .ToListAsync();

// 关联查询
var blog = await db.Blogs
    .Include(b => b.Posts)  // 预加载关联
    .FirstAsync(b => b.Id == 1);

Migration 迁移

bash
dotnet ef migrations add InitialCreate
dotnet ef database update