c# - EF Core - 连接字符串不能为空
问题描述
我正在ASP.Net Core 2.1
使用EF Core 2.1
从 PMC 运行任何迁移时,我收到以下错误
值不能为空。参数名称:连接字符串
这就是我的 Context 类的样子
public class MyAppContextFactory : IDesignTimeDbContextFactory<MyAppContext>
{
private readonly string _dbConnection;
public MyAppContextFactory()
{
}
public MyAppContextFactory(string dbConnection)
: this()
{
_dbConnection = dbConnection;
}
public MyAppContext CreateDbContext(string[] args)
{
var optionsBuilder = new DbContextOptionsBuilder<MyAppContext>();
optionsBuilder.UseSqlServer(_dbConnection, opts => opts.CommandTimeout((int)TimeSpan.FromMinutes(15).TotalSeconds));
return new MyAppContext(optionsBuilder.Options);
}
}
我的连接字符串存在于 appsettings.json 的 API 层中,作为一种好的做法,我不应该在 API/UI 层中添加对 EF 的任何引用。
如何在这种分层架构中根据环境设置连接字符串?
谢谢。
解决方案
我认为 EF 实际上从 2.0 开始启动您的应用程序以生成迁移。您需要将 DesignTimeDbContextFactory 添加到您的项目中,该项目将查询此用例的连接字符串,例如:
public class DesignTimeDbContextFactory : IDesignTimeDbContextFactory<StorageContext>
{
public StorageContext CreateDbContext(string[] args)
{
IConfigurationRoot configuration = new ConfigurationBuilder()
.SetBasePath(Directory.GetCurrentDirectory())
.AddJsonFile("appsettings.json", optional: false)
.AddJsonFile("appsettings.Development.json", optional: true)
.Build();
var builder = new DbContextOptionsBuilder<StorageContext>();
var connectionString = configuration.GetConnectionString("DefaultConnection");
builder.UseSqlServer(connectionString);
Console.WriteLine($"Running DesignTime DB context. ({connectionString})");
return new StorageContext(builder.Options);
}
}
推荐阅读
- functional-programming - 有没有更好的功能方法来处理带有错误检查的向量?
- react-native - StackNavigation 道具未按预期工作
- android - 如何在选定的卡片视图上点击波纹和其他前景?
- wordpress - 强制 Woocommerce 按属性过滤以仅显示搜索词在标题中的属性
- audio - 处理坚持 pause() 不是一个函数,当它非常重要时
- python - 从图像中去除噪点
- google-cloud-platform - 从 Cloudfunctions 提交 Cloudbuild 作业时出错,如果
- string - 如何使用 VB6 获取此字符串的每一行
- sparql - 创建资源中三元组的 SPARQL CONSTRUCT 命令顺序
- functional-programming - 在 F# 中并行柯里化多个函数