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) 极少成为最佳类型,但这些是 EF 使用的默认值,因为 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.