如何使用 Entity Framework 的 DbContext
微軟的 Entity Framework 是一個(gè)開源的 對(duì)象-關(guān)系映射 ORM 框架,它幫助我們打通了 數(shù)據(jù)庫(kù)的數(shù)據(jù)模型 到 代碼層的領(lǐng)域模型,Entity Framework 簡(jiǎn)化了應(yīng)用程序?qū)?shù)據(jù)庫(kù)的 CURD 操作,而且還向高層屏蔽了數(shù)據(jù)是如何持久化到數(shù)據(jù)庫(kù)的。
說(shuō)的具體一點(diǎn)就是 DbContext 充當(dāng)了數(shù)據(jù)庫(kù)到領(lǐng)域模型之間的橋梁,這篇文章我們將會(huì)討論如何配置 DbContext 并使用 Entity Framework Core provider 對(duì)數(shù)據(jù)庫(kù)進(jìn)行 CURD 操作。
DbContext
DbContext 是 EF 中非常重要的一個(gè)組件,它扮演著 Database 的會(huì)話連接,使用它可以查詢數(shù)據(jù)到你的 entitys 集合中,也可以通過(guò)它將 entitys 保存到底層數(shù)據(jù)庫(kù)中, EntityFramework Core 中的 DbContext 擁有如下幾個(gè)功能模塊。
連接管理
查詢數(shù)據(jù)
持久化數(shù)據(jù)
修改跟蹤
緩存
事務(wù)管理
要想使用 EntityFramework,需要通過(guò) nuget 引用 Microsoft.EntityFrameworkCore 包,可以通過(guò) Visual Studio 2019 的 NuGet package manager 可視化界面安裝 或者 通過(guò) NuGet package manager 命令行工具輸入以下命令:
dotnet?add?package?Microsoft.EntityFrameworkCore接下來(lái)討論下如何在 ?ASP.Net Core 中使用 DbContext 。
創(chuàng)建 DbContext
首先創(chuàng)建一個(gè) 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ù),該類主要用于對(duì) DbContext 做一些必要的參數(shù)配置,當(dāng)然你也可以在 OnConfiguring() 中對(duì) DbContext 進(jìn)行配置,接下來(lái)的 OnModelCreating() 方法用于對(duì) model 進(jìn)行配置。
下面我在 CustomContext 中新增幾個(gè) DbSet<TEntity> 屬性用來(lái)表示實(shí)體集合,如下代碼所示:
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;?}}注冊(cè) DbContext 注入到 ASP.NET Core 運(yùn)行時(shí)
要想在 ASP.NET Core 中使用,需要將 CustomerContext 注入到 ServiceCollection 容器中,這里采用 SqlServer 作為底層存儲(chǔ),所以還需要在 NuGet 上引用 Microsoft.EntityFrameworkCore.SqlServer 包,接下來(lái)在 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)注入到容器了,接下來(lái)就可以在 HomeController 中通過(guò)依賴注入的方式獲取 CustomerContext 實(shí)例,下面的代碼片段展示了如何去實(shí)現(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(); 來(lái)確保數(shù)據(jù)庫(kù)已經(jīng)成功創(chuàng)建,執(zhí)行完這句代碼之后,數(shù)據(jù)庫(kù)將會(huì)生成 MyTest 數(shù)據(jù)庫(kù) 和 ?Author,Blog 兩張表結(jié)構(gòu),如下圖所示:
接下來(lái)在 Index 方法中插入一條記錄并查詢,效果如下:
這就是配置 EF 所要做的所有事情,現(xiàn)在你可以利用 CustomContext 去所 CURD 操作了,DbContext 在概念上類似 ObjectContext,表示一個(gè) UnitOfWork ?組合單元,并且 EF 是DDD領(lǐng)域的一個(gè)實(shí)現(xiàn)案例,DbContext 的職責(zé)就是負(fù)責(zé) 應(yīng)用程序 和 數(shù)據(jù)庫(kù) 之間的交互,關(guān)于 Entity Framework Core 的更多特性,我會(huì)放到后面的文章中和大家一起分享。
譯文鏈接:https://www.infoworld.com/article/3311737/how-to-use-the-dbcontext-in-entity-framework-core.html
總結(jié)
以上是生活随笔為你收集整理的如何使用 Entity Framework 的 DbContext的全部?jī)?nèi)容,希望文章能夠幫你解決所遇到的問(wèn)題。
- 上一篇: AgileConfig - RESTfu
- 下一篇: EFCore查缺补漏(一):依赖注入