【发布时间】:2021-03-09 23:23:33
【问题描述】:
目前我正在开发一个 .Net core 3.1 应用程序。我在启动时使用下面的代码来添加 Dbcontext。
services.AddDbContext<sampleContext>(options =>
options.UseSqlServer(Configuration.GetConnectionString("DefaultConnection")));
由于这是我在 Dbcontext 中使用以下代码的代码优先方法
public class sampleContext: DbContext
{
public sampleContext()
{
}
public sampleContext(DbContextOptions<sampleContext> options) : base(options){ }
protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
{
if (!optionsBuilder.IsConfigured)
{
optionsBuilder.UseSqlServer(Environment.GetEnvironmentVariable("DefaultConnection", EnvironmentVariableTarget.Process));
}
}
}
当我运行 API 时,它的工作方式与 optionsBuilder.IsConfigured=true 一样。
Appsettings.json
{
"ConnectionStrings": {
"DefaultConnection": "Server=(localdb)\\MSSQLLocalDB;Initial Catalog=sampleDb; Integrated Security=true;"
},
"Logging": {
"LogLevel": {
"Default": "Information",
"Microsoft": "Warning",
"Microsoft.Hosting.Lifetime": "Information"
}
},
"AllowedHosts": "*",
"UploadFAUrl": "http://localhost:7071/Api"
}
即将发布:-
- 当我运行 CLI 命令时
ADD-MIGRATION sampleCongetting**Value cannot be null. (Parameter 'connectionString')**
为什么会这样?由于我们将移动到不同的环境,我们可能需要运行这个命令。至少在本地,我们需要运行命令。如何解决这个问题?提到了一些问题,但没有帮助。如果我遗漏了什么,请提出建议。
【问题讨论】:
-
您是否将连接字符串存储在 appsettings.json 中,可以给我们看看吗?
-
是的,它在应用程序 settings.json "ConnectionStrings": { "DefaultConnection": "Server=(localdb)\\MSSQLLocalDB;Initial Catalog=sampleDb; Integrated Security=true;" }
-
你能分享你所有的
appsettings.json吗? -
在问题中添加。
-
正如我所解释的,我在运行时没有遇到任何问题。运行迁移命令时只面临问题。 & 在那里我们需要选择 Dbcontext 所在的项目。
标签: c# asp.net-mvc .net-core entity-framework-core asp.net-core-webapi