日韩性视频-久久久蜜桃-www中文字幕-在线中文字幕av-亚洲欧美一区二区三区四区-撸久久-香蕉视频一区-久久无码精品丰满人妻-国产高潮av-激情福利社-日韩av网址大全-国产精品久久999-日本五十路在线-性欧美在线-久久99精品波多结衣一区-男女午夜免费视频-黑人极品ⅴideos精品欧美棵-人人妻人人澡人人爽精品欧美一区-日韩一区在线看-欧美a级在线免费观看

歡迎訪問(wèn) 生活随笔!

生活随笔

當(dāng)前位置: 首頁(yè) > 运维知识 > 数据库 >内容正文

数据库

EF Core 6 简化的数据库上下文注册

發(fā)布時(shí)間:2023/12/4 数据库 25 豆豆
生活随笔 收集整理的這篇文章主要介紹了 EF Core 6 简化的数据库上下文注册 小編覺(jué)得挺不錯(cuò)的,現(xiàn)在分享給大家,幫大家做個(gè)參考.

EF Core 6 簡(jiǎn)化的數(shù)據(jù)庫(kù)上下文注冊(cè)

Intro

EF Core 6 將簡(jiǎn)化現(xiàn)在的服務(wù)注冊(cè),DbContext 的服務(wù)注冊(cè)將會(huì)更簡(jiǎn)單一些

Sample

直接來(lái)看示例代碼吧:

現(xiàn)在我們注冊(cè) EF Core 的 DbContext 通常是這樣的:

const?string?connectionString?=?"DataSource=test"; var?services?=?new?ServiceCollection(); services.AddDbContext<TestDbContext>(options?=>?options.UseSqlite(connectionString));

在 EF Core 6 中將會(huì)得以簡(jiǎn)化成下面的形式:

const?string?connectionString?=?"DataSource=test"; var?services?=?new?ServiceCollection(); services.AddSqlite<TestDbContext>(connectionString);

這兩種方式是完全等價(jià)的

完整示例:

const?string?connectionString?=?"DataSource=test";var?services?=?new?ServiceCollection();services.AddSqlite<TestDbContext>(connectionString);using?var?serviceProvider?=?services.BuildServiceProvider();using?var?scope?=?serviceProvider.CreateScope(); var?dbContext?=?scope.ServiceProvider.GetRequiredService<TestDbContext>(); dbContext.Database.EnsureDeleted(); dbContext.Database.EnsureCreated(); dbContext.Users.Add(new?User? {?Name?=?"Alice",CreatedAt?=?DateTime.UtcNow }); await?dbContext.SaveChangesAsync();var?users?=?await?dbContext.Users.AsNoTracking().ToArrayAsync(); users.Dump();

輸出如下,可以看出來(lái)工作正常

output

示例代碼完整代碼可以從 Github 獲取:https://github.com/WeihanLi/SamplesInPractice/blob/master/EF6Samples/Program.cs

Implement

其實(shí)現(xiàn)方式其實(shí)就是封裝了一個(gè)擴(kuò)展方法,擴(kuò)展方法實(shí)現(xiàn)如下:

public?static?IServiceCollection?AddSqlite<TContext>(this?IServiceCollection?serviceCollection,?string?connectionString,?Action<SqliteDbContextOptionsBuilder>??sqliteOptionsAction?=?null,?Action<DbContextOptionsBuilder>??optionsAction?=?null)where?TContext?:?DbContext {Check.NotNull(serviceCollection,?nameof(serviceCollection));Check.NotEmpty(connectionString,?nameof(connectionString));return?serviceCollection.AddDbContext<TContext>((serviceProvider,?options)?=>{optionsAction?.Invoke(options);options.UseSqlite(connectionString,?sqliteOptionsAction);}); }

更多細(xì)節(jié)可以參考 Github 上的 issue 和 pr

https://github.com/dotnet/efcore/issues/25192

https://github.com/dotnet/efcore/pull/25220

References

  • https://github.com/dotnet/efcore/issues/25192

  • https://github.com/dotnet/efcore/pull/25220

  • https://github.com/WeihanLi/SamplesInPractice/blob/master/EF6Samples/Program.cs

總結(jié)

以上是生活随笔為你收集整理的EF Core 6 简化的数据库上下文注册的全部?jī)?nèi)容,希望文章能夠幫你解決所遇到的問(wèn)題。

如果覺(jué)得生活随笔網(wǎng)站內(nèi)容還不錯(cuò),歡迎將生活随笔推薦給好友。