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的方法就這樣完成了。