【问题标题】:Issue with Connection String with DBcontext in.Net core.Net核心中带有DBcontext的连接字符串问题
【发布时间】: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"
}

即将发布:-

  1. 当我运行 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


【解决方案1】:

EF Core 命令行工具将尝试根据您当前的项目定位所有必需的服务和配置。通过查找您的 CreateHostBuilder 方法并调用它;

public static IHostBuilder CreateHostBuilder(string[] args) => ...

您不需要覆盖OnConfiguring。但您可能需要提供明确的--startup-projectcommand line parameter

【讨论】:

    【解决方案2】:

    您有多个项目吗?

    标记包含Appsettings.json的项目Set as startup project

    【讨论】:

      猜你喜欢
      • 2019-03-10
      • 2017-05-02
      • 2019-09-22
      • 1970-01-01
      • 1970-01-01
      • 2020-07-21
      • 1970-01-01
      • 1970-01-01
      • 2021-08-02
      相关资源
      最近更新 更多