Entity Framework CoreEntity Framework Core

Entity Framework (EF) Core 是常見 Entity Framework 資料存取技術的輕量型、可擴充、開放原始碼且跨平台版本。Entity Framework (EF) Core is a lightweight, extensible, open source and cross-platform version of the popular Entity Framework data access technology.

EF Core 可以作為物件關聯式對應程式 (O/RM) ,其:EF Core can serve as an object-relational mapper (O/RM), which:

  • 可讓 .NET 開發人員使用 .NET 物件來處理資料庫。Enables .NET developers to work with a database using .NET objects.
  • 免除通常需要撰寫的大部分資料存取程式碼的需求。Eliminates the need for most of the data-access code that typically needs to be written.

EF Core 支援許多資料庫引擎,如需詳細資料,請參閱資料庫提供者EF Core supports many database engines, see Database Providers for details.

模型The model

運用 EF Core,使用模型來執行資料存取。With EF Core, data access is performed using a model. 模型是由實體類別和表示與資料庫之會話的內容物件所組成。A model is made up of entity classes and a context object that represents a session with the database. 內容物件可讓您查詢和儲存資料。The context object allows querying and saving data. 如需詳細資訊,請參閱 建立模型For more information, see Creating a Model.

EF 支援下列模型開發方法:EF supports the following model development approaches:

  • 從現有的資料庫產生模型。Generate a model from an existing database.
  • 將模型手動編寫成符合資料庫的程式碼。Hand code a model to match the database.
  • 建立模型之後,請使用 EF 遷移 從模型建立資料庫。Once a model is created, use EF Migrations to create a database from the model. 當模型變更時,遷移可讓資料庫演進。Migrations allow evolving the database as the model changes.
using Microsoft.EntityFrameworkCore;
using System.Collections.Generic;

namespace Intro
{
    public class BloggingContext : DbContext
    {
        public DbSet<Blog> Blogs { get; set; }
        public DbSet<Post> Posts { get; set; }

        protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
        {
            optionsBuilder.UseSqlServer(
                @"Server=(localdb)\mssqllocaldb;Database=Blogging;Integrated Security=True");
        }
    }

    public class Blog
    {
        public int BlogId { get; set; }
        public string Url { get; set; }
        public int Rating { get; set; }
        public List<Post> Posts { get; set; }
    }

    public class Post
    {
        public int PostId { get; set; }
        public string Title { get; set; }
        public string Content { get; set; }

        public int BlogId { get; set; }
        public Blog Blog { get; set; }
    }
}

查詢Querying

您可以使用 (LINQ) 的語言整合式查詢,從資料庫取出實體類別的實例。Instances of your entity classes are retrieved from the database using Language Integrated Query (LINQ). 如需詳細資訊,請參閱 查詢資料For more information, see Querying Data.

using (var db = new BloggingContext())
{
    var blogs = db.Blogs
        .Where(b => b.Rating > 3)
        .OrderBy(b => b.Url)
        .ToList();
}

儲存資料Saving data

使用您實體類別的執行個體,建立、刪除和修改資料庫中的資料。Data is created, deleted, and modified in the database using instances of your entity classes. 若要深入了解,請參閱儲存資料See Saving Data to learn more.

using (var db = new BloggingContext())
{
    var blog = new Blog { Url = "http://sample.com" };
    db.Blogs.Add(blog);
    db.SaveChanges();
}

EF ORM 考慮EF ORM considerations

雖然 EF Core 在抽象化許多程式設計細節時很好用,但還是有一些適用于任何 ORM 的最佳作法,可避免在生產應用程式中發生常見的陷阱:While EF Core is good at abstracting many programming details, there are some best practices applicable to any ORM that help to avoid common pitfalls in production apps:

  • 基礎資料庫伺服器的中繼層級知識或更高版本,對於在高效能的生產環境應用程式中設計、分析、分析和遷移資料而言是不可或缺的。Intermediate-level knowledge or higher of the underlying database server is essential to architect, debug, profile, and migrate data in high performance production apps. 例如,主要與外鍵、條件約束、索引、正規化、DML 和 DDL 語句、資料類型、分析等等的知識。For example, knowledge of primary and foreign keys, constraints, indexes, normalization, DML and DDL statements, data types, profiling, etc.
  • 功能和整合測試:請務必盡可能將生產環境複寫至:Functional and integration testing: It's important to replicate the production environment as closely as possible to:
    • 找出應用程式中只有在使用特定版本的資料庫伺服器時才會顯示的問題。Find issues in the app that only show up when using a specific versions or edition of the database server .
    • 升級 EF Core 和其他相依性時攔截重大變更。Catch breaking changes when upgrading EF Core and other dependencies. 例如,加入或升級 ASP.NET Core、OData 或 Automapper 等架構。For example, adding or upgrading frameworks like ASP.NET Core, OData, or Automapper. 這些相依性可能會以非預期的方式影響 EF Core。These dependencies can affect EF Core in unexpected ways.
  • 具有代表性負載的效能和壓力測試。Performance and stress testing with representative loads. 部分功能的最簡單用途無法妥善調整。The naïve usage of some features doesn't scale well. 例如,多個集合包括過度使用消極式載入、非索引資料行上的條件式查詢、具有存放區產生值的大量更新和插入、缺乏並行處理、大型模型、不適當的快取原則。For example, multiple collections Includes, heavy use of lazy loading, conditional queries on non-indexed columns, massive updates and inserts with store-generated values, lack of concurrency handling, large models, inadequate cache policy.
  • 安全性審核:例如,處理連接字串和其他秘密、非部署作業的資料庫許可權、原始 SQL 的輸入驗證、機密資料的加密。Security review: For example, handling of connection strings and other secrets, database permissions for non-deployment operation, input validation for raw SQL, encryption for sensitive data.
  • 請確定記錄和診斷功能足夠且可用。Make sure logging and diagnostics are sufficient and usable. 例如,適當的記錄設定、查詢標記以及 Application Insights。For example, appropriate logging configuration, query tags, and Application Insights.
  • 錯誤復原。Error recovery. 針對常見的失敗案例(例如版本復原、回溯伺服器、向外延展和負載平衡、DoS 緩和和資料備份)做好應變。Prepare contingencies for common failure scenarios such as version rollback, fallback servers, scale-out and load balancing, DoS mitigation, and data backups.
  • 應用程式部署和遷移。Application deployment and migration. 規劃如何在部署期間套用遷移;在應用程式啟動時執行它可能會受到並行處理問題的影響,且需要的許可權比一般作業所需的更高。Plan out how migrations are going to be applied during deployment; doing it at application start can suffer from concurrency issues and requires higher permissions than necessary for normal operation. 使用暫存有助於在遷移期間發生嚴重錯誤時進行修復。Use staging to facilitate recovery from fatal errors during migration. 如需詳細資訊,請參閱套用 遷移For more information, see Applying Migrations.
  • 已產生之遷移的詳細檢查和測試。Detailed examination and testing of generated migrations. 在將遷移套用至生產資料之前,應先徹底測試。Migrations should be thoroughly tested before being applied to production data. 當資料表包含生產資料時,架構的圖形和資料行類型不容易變更。The shape of the schema and the column types cannot be easily changed once the tables contain production data. 例如,在 SQL Server 上, nvarchar(max)decimal(18, 2) 不是對應至字串和 decimal 屬性之資料行的最佳類型,但這些是 EF 使用的預設值,因為它並不知道您的特定案例。For example, on SQL Server, nvarchar(max) and decimal(18, 2) are rarely the best types for columns mapped to string and decimal properties, but those are the defaults that EF uses because it doesn't have knowledge of your specific scenario.

後續步驟Next steps

如需簡介教學課程,請參閱 Entity Framework Core 使用者入門For introductory tutorials, see Getting Started with Entity Framework Core.