首页 文章详情

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

DotNet NB | 325 2021-09-23 20:32 0 0 0
UniSMS (合一短信)

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

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

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
推荐阅读:
Kubernetes全栈架构师(Kubeadm高可用安装k8s集群)--学习笔记
.NET 云原生架构师训练营(模块一 架构师与云原生)--学习笔记
.NET Core开发实战(第1课:课程介绍)--学习笔记

点击下方卡片关注DotNet NB

一起交流学习

▲ 点击上方卡片关注DotNet NB,一起交流学习

请在公众号后台


 回复 【路线图】获取.NET 2021开发者路线图
 回复 【原创内容】获取公众号原创内容
 回复 【峰会视频】获取.NET Conf开发者大会视频
 回复 【个人简介】获取作者个人简介
 回复 【年终总结】获取作者年终总结
 回复 加群加入DotNet NB 交流学习群

长按识别下方二维码,或点击阅读原文。和我一起,交流学习,分享心得。


good-icon 0
favorite-icon 0
收藏
回复数量: 0
    暂无评论~~
    Ctrl+Enter