简体   繁体   中英

Issue with Connection String with DBcontext in.Net core

Currently i am working on a.Net core 3.1 App. I am using below code in the startup to Add the Dbcontext.

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

As this is the code first approach i have below code in the 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 .

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"
}

Coming to issue:-

  1. When i am running the CLI command ADD-MIGRATION sampleCon getting **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. By looking for your CreateHostBuilder method, and calling it;

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

You shouldn't need to override OnConfiguring . But you may need to provide an explicit --startup-project command line parameter .

Do you have multiple projects?

Mark the project Set as startup project which contains Appsettings.json .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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