简体   繁体   English

.Net核心中带有DBcontext的连接字符串问题

[英]Issue with Connection String with DBcontext in.Net core

Currently i am working on a.Net core 3.1 App.目前我正在开发 a.Net core 3.1 App。 I am using below code in the startup to Add the Dbcontext.我在启动时使用下面的代码来添加 Dbcontext。

services.AddDbContext<sampleContext>(options =>
                options.UseSqlServer(Configuration.GetConnectionString("DefaultConnection")));

As this is the code first approach i have below code in the Dbcontext因为这是代码优先的方法,所以我在 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));
            }
        }
}

When i am running the API, its working as expected as optionsBuilder.IsConfigured=true .当我运行 API 时,它的工作方式与optionsBuilder.IsConfigured=true一样。

Appsettings.json应用设置.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"
}

Coming to issue:-即将发布:-

  1. When i am running the CLI command ADD-MIGRATION sampleCon getting **Value cannot be null. (Parameter 'connectionString')**当我运行 CLI 命令ADD-MIGRATION sampleCon获取**Value cannot be null. (Parameter 'connectionString')** **Value cannot be null. (Parameter 'connectionString')**

Whys is so?为什么会这样? As we will be moving to different env, we may need to run this command.由于我们将移动到不同的环境,我们可能需要运行这个命令。 Atleast in local, we need to run the command.至少在本地,我们需要运行命令。 How to fix this issue?如何解决这个问题? Referred some of the question but non helped.提到了一些问题,但没有帮助。 PLease suggest if i am missing anything.请建议我是否遗漏任何东西。

The EF Core command line tools, will attempt to locate all required services and configuration, based on your current project. EF Core 命令行工具将尝试根据您当前的项目定位所有必需的服务和配置。 By looking for your CreateHostBuilder method, and calling it;通过查找您的CreateHostBuilder方法并调用它;

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

You shouldn't need to override OnConfiguring .您不需要覆盖OnConfiguring But you may need to provide an explicit --startup-project command line parameter .但是您可能需要提供一个明确的--startup-project 命令行参数

Do you have multiple projects?你有多个项目吗?

Mark the project Set as startup project which contains Appsettings.json .将项目Set as startup project包含Appsettings.json的启动项目。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM