基本查詢Basic Queries

了解如何使用 Language Integrated Query (LINQ) 從資料庫載入實體。Learn how to load entities from the database using Language Integrated Query (LINQ).

提示

您可以在 GitHub 上檢視此文章的範例 (英文)。You can view this article's sample on GitHub.

101 個 LINQ 範例101 LINQ samples

此頁面會顯示可使用 Entity Framework Core 來達成常見工作的一些範例。This page shows a few examples to achieve common tasks with Entity Framework Core. 如需示範使用 LINQ 可能性的大量範例,請參閱 101 個 LINQ 範例 (英文)。For an extensive set of samples showing what is possible with LINQ, see 101 LINQ Samples.

載入所有資料Loading all data

using (var context = new BloggingContext())
{
    var blogs = context.Blogs.ToList();
}

載入單一實體Loading a single entity

using (var context = new BloggingContext())
{
    var blog = context.Blogs
        .Single(b => b.BlogId == 1);
}

篩選Filtering

using (var context = new BloggingContext())
{
    var blogs = context.Blogs
        .Where(b => b.Url.Contains("dotnet"))
        .ToList();
}