一.概述
本章使用 Entity Framework Core 构建执行基本数据访问的 ASP.NET Core MVC 应用程序。使用迁移(migrations)基于数据模型创建数据库,是一种code first模式。可以在Windows 上使用 Visual Studio 2017,或在 Windows、macOS 或 Linux 上使用 .NET Core CLI 来学习。已经安装了NET Core 2.1 SDK,这里使用Visual Studio 2017和sql server 2012演示。
1.1 创建新项目
(1) 打开 Visual Studio 2017
(2) 选择 ASP.NET Core Web 应用程序。
(3) 输入 EFGetStarted.AspNetCore.NewDb 作为名称。
(4) 在新建 ASP.NET Core Web 应用程序 对话框中:
确保在下拉列表中选择“.NET Core”和“ASP.NET Core 2.2”
选择“Web 应用程序(模型视图控制器)”项目模板
确保将“身份验证”设置为“无身份验证”
(5) 编译
出错:“任务不支持“SharedCompilationId”参数。请确认该参数存在于此任务中” ,安装如下:
PM> install-package Microsoft.Net.Compilers
1.2 安装 Entity Framework Core
要安装 EF Core,需要把目标对象的 EF Core 数据库提供程序安装。本篇使用SQL Server数据库,需要安装 SQL Server 提供程序包。
install-package Microsoft.EntityFrameworkCore.SqlServer -Version 2.2.0

1.3 创建模型
右键单击“Models”文件夹,然后选择“添加”>“类。输入“Model.cs”作为名称。
/// <summary> /// 创建模型 /// using Microsoft.EntityFrameworkCore; /// </summary> public class BloggingContext : DbContext { public BloggingContext(DbContextOptions<BloggingContext> options) : base(options) { } public DbSet<Blog> Blogs { get; set; } public DbSet<Post> Posts { get; set; } } public class Blog { public int BlogId { get; set; } public string Url { get; set; } public ICollection<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; } }
1.4 使用依赖注入注册上下文
服务(例如 BloggingContext)在应用程序启动期间通过依赖关系注入进行注册。 需要这些服务的组件(如 MVC 控制器)可以通过向构造函数或属性添加相关参数来获得对应服务。
public void ConfigureServices(IServiceCollection services) { services.Configure<CookiePolicyOptions>(options => { // This lambda determines whether user consent for non-essential cookies is needed for a given request. options.CheckConsentNeeded = context => true; options.MinimumSameSitePolicy = SameSiteMode.None;

