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

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

Intro

EF Core 6 将简化现在的服务注册,DbContext 的服务注册将会更简单一些

Sample

直接来看示例代码吧:

现在我们注册 EF Core 的 DbContext 通常是这样的:

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

在 EF Core 6 中将会得以简化成下面的形式:

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

这两种方式是完全等价的

完整示例:

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();

输出如下,可以看出来工作正常

7c31a58e91b2085eb5063e821abb3be4.png

output

示例代码完整代码可以从 Github 获取:https://github.com/WeihanLi/SamplesInPractice/blob/master/EF6Samples/Program.cs

Implement

其实现方式其实就是封装了一个扩展方法,扩展方法实现如下:

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);
    });
}

更多细节可以参考 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

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值