Issue with Connection String with DBcontext in.Net core

Viewed 268

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 sampleCongetting **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.

2 Answers

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.

Related