一、什么是EF
Entity Framework 是适用于.NET 的对象关系映射程序 (O/RM)。
二、比较 EF Core 和 EF6
1.Entity Framework 6
Entity Framework 6 (EF6) 是一种久经验证的数据访问技术。(仅在Windows上运行)
2.Entity Framework Core
Entity Framework Core (EF Core) 是在 2016 年首次发布的 EF6 的完全重写。 它附带于 Nuget 包中,是 Microsoft.EntityFrameworkCore 的主要组成部分。 EF Core 是一种跨平台产品,可以在 .NET Core 或 .NET Framework 上运行。
三、安装 EF Core
1.获取EF Core 运行时(CRL)
(运行时:运行时是指一个程序在运行(或者在被执行)的状态,也可粗略理解为运行环境)
打开项目的NuGet包 ---->添加包:Pomelo.EntityFrameworkCore.MySql
四、新建项目(新建数据库或原有数据库)
1.前提:新建 ASP .Net Core Web应用程序(MVC),名称:TestEFCore
2.新建数据库
(1)在model文件夹下新建类:TestEfContext
usingMicrosoft.EntityFrameworkCore;usingSystem;usingSystem.Collections.Generic;usingSystem.Linq;usingSystem.Threading.Tasks;namespaceTestEFCore.Models
{public classTestEfContext: DbContext
{public TestEfContext(DbContextOptionsoptions)
:base(options)
{ }public DbSet Blogs { get; set; }public DbSet Posts { get; set; }
}public classBlog
{public int BlogId { get; set; }public string Url { get; set; }public ICollection Posts { get; set; }
}public classPost
{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; }
}
}
(2)使用依赖注入注册上下文
服务(例如TestEfContext)在应用程序启动期间通过依赖关系注入进行注册。 需要这些服务的组件(如 MVC 控制器)可以通过向构造函数或属性添加相关参数来获得对应服务。
编辑 Startup.cs
public voidConfigureServices(IServiceCollection services)
{
services.Configure(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;
});
services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_1);//连接字符串
var connection = "server=127.0.0.1;userid=root;pwd=root;port=3306;database=TestEf;sslmode=none;Convert Zero Datetime=True";//使用依赖注入把BloggingContext注册为服务
services.AddDbContext(options =>options.UseMySql(connection));
}
(注:如果此时提示UseMySql缺少引用,请检查是否添加Pomelo.EntityFrameworkCore.MySql包)
(3)使用迁移创建数据库
“工具”>“NuGet 包管理器”>“包管理器控制台”
运行以下命令
Add-Migration Init
Update-Database
2.通过现有数据库在ASP .NET Core上开始使用EF Core
(1)使用sql语句创建数据库
CREATE DATABASE TestEfReverse;
USE TestEfReverse;
CREATE TABLE Blog (
BlogId int NOT NULL auto_increment,
Url nvarchar(225) NOT NULL,
CONSTRAINT PK_Blog PRIMARY KEY (BlogId)
);
CREATE TABLE Post(
PostId int NOT NULL auto_increment,
BlogId int NOT NULL,
Content text,
Title text,
CONSTRAINT PK_Post PRIMARY KEY (PostId),
CONSTRAINT FK_Post_Blog_BlogId FOREIGN KEY (BlogId) REFERENCES Blog (BlogId) ON DELETE CASCADE
);
(2)对模型实施反向工程(基于现有数据库创建Model)
“工具”–>“NuGet 包管理器”–>“包管理器控制台”
运行以下PowerShell
Scaffold-DbContext "server=127.0.0.1;userid=root;pwd=root;port=3306;database=TestEfReverse;sslmode=none;Convert Zero Datetime=True" Pomelo.EntityFrameworkCore.MySql -OutputDir Models
反向工程过程基于现有数据库的架构创建实体类 (Blog.cs & Post.cs) 和派生上下文 (TestEfReverseContext.cs)。
(3)通过依赖关系把TestEfReverseContext注册成服务(新建数据库操作一致)