网站集约化建设管理方案,wordpress加cnzz统计在那里加,开个网要多少钱,企业建站服务退役军人EF Core 6 简化的数据库上下文注册IntroEF Core 6 将简化现在的服务注册#xff0c;DbContext 的服务注册将会更简单一些Sample直接来看示例代码吧#xff1a;现在我们注册 EF Core 的 DbContext 通常是这样的#xff1a;const string connectionString DataSourcete… EF Core 6 简化的数据库上下文注册IntroEF Core 6 将简化现在的服务注册DbContext 的服务注册将会更简单一些Sample直接来看示例代码吧现在我们注册 EF Core 的 DbContext 通常是这样的const string connectionString DataSourcetest;
var services new ServiceCollection();
services.AddDbContextTestDbContext(options options.UseSqlite(connectionString));在 EF Core 6 中将会得以简化成下面的形式const string connectionString DataSourcetest;
var services new ServiceCollection();
services.AddSqliteTestDbContext(connectionString);这两种方式是完全等价的完整示例const string connectionString DataSourcetest;var services new ServiceCollection();services.AddSqliteTestDbContext(connectionString);using var serviceProvider services.BuildServiceProvider();using var scope serviceProvider.CreateScope();
var dbContext scope.ServiceProvider.GetRequiredServiceTestDbContext();
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.csImplement其实现方式其实就是封装了一个扩展方法扩展方法实现如下public static IServiceCollection AddSqliteTContext(this IServiceCollection serviceCollection, string connectionString, ActionSqliteDbContextOptionsBuilder? sqliteOptionsAction null, ActionDbContextOptionsBuilder? optionsAction null)where TContext : DbContext
{Check.NotNull(serviceCollection, nameof(serviceCollection));Check.NotEmpty(connectionString, nameof(connectionString));return serviceCollection.AddDbContextTContext((serviceProvider, options) {optionsAction?.Invoke(options);options.UseSqlite(connectionString, sqliteOptionsAction);});
}更多细节可以参考 Github 上的 issue 和 prhttps://github.com/dotnet/efcore/issues/25192https://github.com/dotnet/efcore/pull/25220Referenceshttps://github.com/dotnet/efcore/issues/25192https://github.com/dotnet/efcore/pull/25220https://github.com/WeihanLi/SamplesInPractice/blob/master/EF6Samples/Program.cs