EF Core 通過數據庫提供程序插件模型與 SQL Server/SQL Azure、SQLite、Azure Cosmos DB、MySQL、PostgreSQL 和更多數據庫配合使用。
使用EF Core 的優點
Entity Framework (EF) Core 是輕量化、可擴展、開源和跨平台版的常用 Entity Framework 數據訪問技術。
EF Core 可用作對象關系映射程序 (O/RM),這可以實現以下兩點:
- 使 .NET 開發人員能夠使用 .NET 對象處理數據庫。
- 無需再像通常那樣編寫大部分數據訪問代碼。
在開始使用EF Core的時候我們需要在項目中引用一些包 使用NuGet管理器直接引入即可 包名如下:
Micorsoft.EntityFrameworkCore:EF框架的核心包
Micorsoft.EntityFrameworkCore.SqlServer:針對SqlServer數據庫的擴展
其他包是為了生成實體使用的。
EF Core不支持用於可視化設計器的DB模型和向導來創建類似於EF 6的實體和上下文類。所以我們需要使用命令來生成。
Scaffold-DbContext命令
Scaffold-DbContext [-Connection] [-Provider] [-OutputDir] [-Context] [-Schemas>] [-Tables>]
[-DataAnnotations] [-Force] [-Project] [-StartupProject] [<CommonParameters>]
參數說明:
-OutputDir *** 實體文件所存放的文件目錄 -ContextDir *** DbContext文件存放的目錄 -Context *** DbContext文件名 -Schemas *** 需要生成實體數據的數據表所在的模式 -Tables *** 需要生成實體數據的數據表的集合 -DataAnnotations -UseDatabaseNames 直接使用數據庫中的表名和列名(某些版本不支持) -Force 強制執行,重寫已經存在的實體文件
在VS2019NuGet程序包管理器控制台運行如下命令:
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的方法就這樣完成了。