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),以便于 .NET 开发人员能够使用 .NET 对象来处理数据库,这样就不必经常编写大部分数据访问代码了。EF Core can serve as an object-relational mapper (O/RM), enabling .NET developers to work with a database using .NET objects, and eliminating the need for most of the data-access code they usually need to write.

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, allowing you to query and save data. 有关详细信息,请参阅创建模型See Creating a Model to learn more.

可以根据现有数据库生成模型,手动将模型编码为与数据库匹配,也可以使用 EF 迁移根据模型创建数据库,然后在模型随时间推移发生更改时改进它。You can generate a model from an existing database, hand code a model to match your database, or use EF Migrations to create a database from your model, and then evolve it as your model changes over time.

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). 有关详细信息,请参阅查询数据See Querying Data to learn more.

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();
}

后续步骤Next steps

有关介绍性教程,请参阅 Entity Framework Core 入门For introductory tutorials, see Getting Started with Entity Framework Core.