'.NET Core: How can I set the connection string?

I am trying to use Blazor's CRUD functions and following some article to do this. In the article, there is a part that I should put my connection in context file, but it doesn't say how to set the connection string.

I put this code line in launchSettings.json:

{
  "ConnectionStrings": {
    "UserDatabase": "Server=DESKTOP-2K2A6GN;Database=Assignment4;Trusted_Connection=True;"
  },
  "iisSettings": {
    "windowsAuthentication": false,
    "anonymousAuthentication": true,
    "iisExpress": {
      "applicationUrl": "http://localhost:56244/",
      "sslPort": 0
    }
  },
  "profiles": {
    "IIS Express": {
      "commandName": "IISExpress",
      "launchBrowser": true,
      "environmentVariables": {
        "ASPNETCORE_ENVIRONMENT": "Development"
      }
    },
    "Assignment4.Server": {
      "commandName": "Project",
      "launchBrowser": true,
      "environmentVariables": {
        "ASPNETCORE_ENVIRONMENT": "Development"
      },
      "applicationUrl": "http://localhost:56248/"
    }
  }
}

And I tried to add the connection string into the context file, but it didn't work.

public class UserContext : DbContext
    {
        public virtual DbSet<User> tblUser { get; set; }

        protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
        {
            if (!optionsBuilder.IsConfigured)
            {
                optionsBuilder.UseSqlServer(@"UserDatabase");
            }
        }
    }


Solution 1:[1]

Connection string settings are suppose to be in the appsetting.json file. Add the file to the project

appsetting.json

{
  "ConnectionStrings": {
    "UserDatabase": "Server=DESKTOP-2K2A6GN;Database=Assignment4;Trusted_Connection=True;"
  }
}

Update the DbContext so that it can be configured.

public class UserContext : DbContext {

    public UserContext(DbContextOptions<UserContext> options): base(options) {

    }

    public virtual DbSet<User> tblUser { get; set; }

}

You would configure the DbContext in the Startupclass in the ConfigureServices method.

public class Startup {

    public Startup(IHostingEnvironment env) {

        var builder = new ConfigurationBuilder()
            .SetBasePath(env.ContentRootPath)
            .AddJsonFile("appsettings.json");

        Configuration = builder.Build();
    }

    static IConfiguration Configuration { get; set; }

    public void ConfigureServices(IServiceCollection services) {    

        services.AddDbContext<UserContext>(options =>
            options.UseSqlServer(Configuration.GetConnectionString("UserDatabase"));
        );

        //...
    }

    // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
    public void Configure(IApplicationBuilder app, IHostingEnvironment env) {
        if (env.IsDevelopment()) {
            app.UseDeveloperExceptionPage();
        }

        app.UseBlazor<Client.Program>();
    }
}

Solution 2:[2]

You can change in file UserContext.cs

public class DesignTimeDbContextFactory : IDesignTimeDbContextFactory<AppDbContext>
    {
        public UserContext CreateDbContext(string[] args)
        {
            IConfiguration configuration = new ConfigurationBuilder()
                .SetBasePath(Directory.GetCurrentDirectory())
                .AddJsonFile("appsettings.json").Build();
            var builder = new DbContextOptionsBuilder<AppDbContext>();
            var connectionString = configuration.GetConnectionString("UserDatabase");
            builder.UseSqlServer(connectionString);
            return new AppDbContext(builder.Options);
        }
    }

And in file Startup.cs

public void ConfigureServices(IServiceCollection services)
    {
        services.AddDbContext<UserContext>(options =>
               options.UseSqlServer(Configuration.GetConnectionString("UserDatabase"),
                   b => b.MigrationsAssembly("xxx.Data")));
    }

Solution 3:[3]

I know I'm late to the party here, but if you do want to set the connection string in launchSettings.json, you can create an environment variable called ConnectionStrings:YourConnectionStringName, then it will get picked up as a connection string.

In your specific example:

{
  "iisSettings": {
    "windowsAuthentication": false,
    "anonymousAuthentication": true,
    "iisExpress": {
      "applicationUrl": "http://localhost:56244/",
      "sslPort": 0
    }
  },
  "profiles": {
    "IIS Express": {
      "commandName": "IISExpress",
      "launchBrowser": true,
      "environmentVariables": {
        "ASPNETCORE_ENVIRONMENT": "Development",
        "ConnectionStrings:UserDatabase": "Server=DESKTOP-2K2A6GN;Database=Assignment4;Trusted_Connection=True;"
      }
    },
    "Assignment4.Server": {
      "commandName": "Project",
      "launchBrowser": true,
      "environmentVariables": {
        "ASPNETCORE_ENVIRONMENT": "Development",
        "ConnectionStrings:UserDatabase": "Server=DESKTOP-2K2A6GN;Database=Assignment4;Trusted_Connection=True;"
      },
      "applicationUrl": "http://localhost:56248/"
    }
  }
}

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1
Solution 2 hiimdat95
Solution 3 Erik A. Brandstadmoen