EF Core 经过数据库提供程序插件模型与 SQL Server/SQL Azure、SQLite、Azure Cosmos DB、MySQL、PostgreSQL 和更多数据库配合使用。git
使用EF Core 的优势github
Entity Framework (EF) Core 是轻量化、可扩展、开源和跨平台版的经常使用 Entity Framework 数据访问技术。数据库
EF Core 可用做对象关系映射程序 (O/RM),这能够实现如下两点:json
在开始使用EF Core的时候咱们须要在项目中引用一些包 使用NuGet管理器直接引入便可 包名以下:app
Micorsoft.EntityFrameworkCore:EF框架的核心包
Micorsoft.EntityFrameworkCore.SqlServer:针对SqlServer数据库的扩展cors
其余包是为了生成实体使用的。框架
EF Core不支持用于可视化设计器的DB模型和向导来建立相似于EF 6的实体和上下文类。因此咱们须要使用命令来生成。ide
Scaffold-DbContext [-Connection] [-Provider] [-OutputDir] [-Context] [-Schemas>] [-Tables>]
[-DataAnnotations] [-Force] [-Project] [-StartupProject] [<CommonParameters>]
参数说明:ui
-OutputDir *** 实体文件所存放的文件目录 -ContextDir *** DbContext文件存放的目录 -Context *** DbContext文件名 -Schemas *** 须要生成实体数据的数据表所在的模式 -Tables *** 须要生成实体数据的数据表的集合 -DataAnnotations -UseDatabaseNames 直接使用数据库中的表名和列名(某些版本不支持) -Force 强制执行,重写已经存在的实体文件
在VS2019NuGet程序包管理器控制台运行以下命令:spa
Scaffold-DbContext "Server=.;Database=DBName;Trusted_Connection=True;" Microsoft.EntityFrameworkCore.SqlServer -OutputDir Models
,命令运行成功以后生成以下类 链接字符串在Context类里面
protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder) { if (!optionsBuilder.IsConfigured) { //#warning To protect potentially sensitive information in your connection string, you should move it out of source code. You can avoid scaffolding the connection string by using the Name= syntax to read it from configuration - see https://go.microsoft.com/fwlink/?linkid=2131148. For more guidance on storing connection strings, see http://go.microsoft.com/fwlink/?LinkId=723263. optionsBuilder.UseSqlServer(@"Server=.;Database=CloudCollector;Trusted_Connection=True;"); } }
使用“new”的简单的 DbContext 初始化
在业务逻辑类里面使用using new DbContext 来初始化DbContext
public Cloud Get(int id) { using (var db = new CloudCollectorContext()) { var result = db.Clouds.Where(t => t.Status == 1&&t.Id==id).FirstOrDefault(); return result; } }
ASP.NET Core 依赖关系注入中的 DbContext
在.NetCore中开发要求须要IOC 因此咱们须要在MVC的Startup的ConfigureServices方法中注册DbContext 注册代码以下
services.AddDbContext<CloudCollectorContext>( options => options.UseSqlServer("name=ConnectionStrings:DefaultConnection"));
appsettings.json文件配置以下:
"ConnectionStrings": { "DefaultConnection": "Server=.;Database=CloudCollector;Trusted_Connection=True;" }
如此咱们即可以使用依赖注入方式实现DbContext初始化了
public Cloud Get(int id) { var result=_context.Clouds.Where(t => t.Status == 1 && t.Id == id).FirstOrDefault(); return result; }
整个EFCore链接数据库初始化DbContext的方法就这样完成了。