如何使用 Entity Framework 的 DbContext
本文轉(zhuǎn)載自微信公眾號「碼農(nóng)讀書」,作者碼農(nóng)讀書 。轉(zhuǎn)載本文請聯(lián)系碼農(nóng)讀書公眾號。
微軟的 Entity Framework 是一個開源的 對象-關(guān)系映射 ORM 框架,它幫助我們打通了 數(shù)據(jù)庫的數(shù)據(jù)模型 到 代碼層的領(lǐng)域模型,Entity Framework 簡化了應(yīng)用程序?qū)?shù)據(jù)庫的 CURD 操作,而且還向高層屏蔽了數(shù)據(jù)是如何持久化到數(shù)據(jù)庫的。
說的具體一點就是 DbContext 充當(dāng)了數(shù)據(jù)庫到領(lǐng)域模型之間的橋梁,這篇文章我們將會討論如何配置 DbContext 并使用 Entity Framework Core provider 對數(shù)據(jù)庫進行 CURD 操作。
DbContext
DbContext 是 EF 中非常重要的一個組件,它扮演著 Database 的會話連接,使用它可以查詢數(shù)據(jù)到你的 entitys 集合中,也可以通過它將 entitys 保存到底層數(shù)據(jù)庫中, EntityFramework Core 中的 DbContext 擁有如下幾個功能模塊。
- 連接管理
- 查詢數(shù)據(jù)
- 持久化數(shù)據(jù)
- 修改跟蹤
- 緩存
- 事務(wù)管理
要想使用 EntityFramework,需要通過 nuget 引用 Microsoft.EntityFrameworkCore 包,可以通過 Visual Studio 2019 的 NuGet package manager 可視化界面安裝 或者 通過 NuGet package manager 命令行工具輸入以下命令:
- dotnet add package Microsoft.EntityFrameworkCore
接下來討論下如何在 ASP.Net Core 中使用 DbContext 。
創(chuàng)建 DbContext
首先創(chuàng)建一個 CustomContext 類,并繼承 Entity Framework 中的基類 DbContext,如下代碼所示:
- public class CustomContext : DbContext
- {
- public CustomContext(DbContextOptions options) : base(options)
- {
- }
- protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
- {
- //Write your code here to configure the context
- }
- protected override void OnModelCreating(ModelBuilder modelBuilder)
- {
- //Write your code here to configure the model
- }
- }
可以看到 CustomContext 的構(gòu)造函數(shù)中接受了 DbContextOptions 類型的參數(shù),該類主要用于對 DbContext 做一些必要的參數(shù)配置,當(dāng)然你也可以在 OnConfiguring() 中對 DbContext 進行配置,接下來的 OnModelCreating() 方法用于對 model 進行配置。
下面我在 CustomContext 中新增幾個 DbSet
- public class CustomContext : DbContext
- {
- public CustomContext(DbContextOptions options) : base(options)
- {
- }
- protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
- {
- }
- protected override void OnModelCreating(ModelBuilder modelBuilder)
- {
- }
- public DbSet<Author> Authors { get; set; }
- public DbSet<Blog> Blogs { get; set; }
- }
- public class Author
- {
- public int AuthorID { get; set; }
- public string AuthorName { get; set; }
- }
- public class Blog
- {
- public int BlogID { get; set; }
- public string BlogName { get; set; }
- public int AuthorID { get; set; }
- }
注冊 DbContext 注入到 ASP.NET Core 運行時
要想在 ASP.NET Core 中使用,需要將 CustomerContext 注入到 ServiceCollection 容器中,這里采用 SqlServer 作為底層存儲,所以還需要在 NuGet 上引用 Microsoft.EntityFrameworkCore.SqlServer 包,接下來在 Startup.ConfigureServices() 中新增如下代碼:
- public class Startup
- {
- // This method gets called by the runtime. Use this method to add services to the container.
- public void ConfigureServices(IServiceCollection services)
- {
- services.AddControllersWithViews();
- services.AddDbContext<CustomContext>(options => options.UseSqlServer("Data Source=.; Initial Catalog=MyTest; Trusted_Connection=Yes"));
- }
- }
DbContext 依賴注入
現(xiàn)在 CustomContext 已經(jīng)注入到容器了,接下來就可以在 HomeController 中通過依賴注入的方式獲取 CustomerContext 實例,下面的代碼片段展示了如何去實現(xiàn)。
- public class HomeController : Controller
- {
- ILogger<HomeController> logger;
- private CustomContext dbContext;
- public HomeController(ILogger<HomeController> logger, CustomContext dbContext)
- {
- this.logger = logger;
- this.dbContext = dbContext;
- dbContext.Database.EnsureCreated();
- }
- }
上面的代碼,我用了 dbContext.Database.EnsureCreated(); 來確保數(shù)據(jù)庫已經(jīng)成功創(chuàng)建,執(zhí)行完這句代碼之后,數(shù)據(jù)庫將會生成 MyTest 數(shù)據(jù)庫 和 Author,Blog 兩張表結(jié)構(gòu),如下圖所示:
接下來在 Index 方法中插入一條記錄并查詢,效果如下:
這就是配置 EF 所要做的所有事情,現(xiàn)在你可以利用 CustomContext 去所 CURD 操作了,DbContext 在概念上類似 ObjectContext,表示一個 UnitOfWork 組合單元,并且 EF 是DDD領(lǐng)域的一個實現(xiàn)案例,DbContext 的職責(zé)就是負(fù)責(zé) 應(yīng)用程序 和 數(shù)據(jù)庫 之間的交互,關(guān)于 Entity Framework Core 的更多特性,我會放到后面的文章中和大家一起分享。
譯文鏈接:https://www.infoworld.com/article/3311737/how-to-use-the-dbcontext-in-entity-framework-core.html