How do I set up a connection string into appsettings.json?

Viewed 4513

How can I set up a connection string in my ASP.NET Core blazor WebAssembly Server component where I created the appsettings.json.

{
  "ConnectionStrings": {
    "SQLiteTestConnection": "Data Source=./TestDB.db",
  }
}

Right now it looks like this but I cant create the database via Update-Database.

Startup.cs:

...
 public void ConfigureServices(IServiceCollection services)
        {
            services.AddMvc();
            services.AddResponseCompression(opts =>
            {
                opts.MimeTypes = ResponseCompressionDefaults.MimeTypes.Concat(
                    new[] { "application/octet-stream" });
            });

            // Adding the DbContext references
            services.AddDbContext<SQLiteTestDbContext>(options =>
                options.UseSqlite("./TestDB.db"));
        }
...

my DbContext which is in use. This DbContext is stored in my Blazor Server component

using DB_SQLite;
using DB_SQLite.SQL_Models;
using System.Collections.Generic;
using Microsoft.EntityFrameworkCore;

namespace BlazorWeb.Server.Data
{
    public class SQLiteTestDbContext : DbContext
    {
        #region Constructor

        // Default parameterless Constructor 
        public SQLiteTestDbContext(DbContextOptions options)
            : base(options)
        {

        }

        #endregion


        public DbSet<ObjectModel> Objects { get; set; }


        protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
            => optionsBuilder.UseSqlite("Data Source=./TestDB.db");


        protected override void OnModelCreating(ModelBuilder modelBuilder)
        {
            #region Configure Object


            modelBuilder.Entity<ObjectModel>().HasData(LoadObjects());
            base.OnModelCreating(modelBuilder);

            #endregion
        }

        #region Seeding

        private List<ObjectModel> LoadObjects()
        {
            return new List<ObjectModel>
            {
                new ObjectModel() { Id = 1, Name = "Schraube", TagName = "Werkzeug" ,PreviewImage = "null"},
                new ObjectModel() { Id = 2, Name = "Gabelstapler", TagName = "Fahrzeug" ,PreviewImage = "null"},
                new ObjectModel() { Id = 3, Name = "Zange", TagName = "Werkzeug" , PreviewImage = "null"},
                new ObjectModel() { Id = 4, Name = "Sechskantschraube", TagName = "Werkzeug", PreviewImage = "null"},
            };
        }

        #endregion
    }
}

Im also creating some fake data into the database in the DbContext Class.

1 Answers

In your Startup.cs class declare an instance of IConfiguration as a field and initialize it in the constructor.

public class Startup
{
    private IConfiguration Configuration { get; }

    public Startup()
    {
        var configurationBuilder = new ConfigurationBuilder()
            .AddJsonFile("appsettings.json", true, false);

        Configuration = configurationBuilder.Build();
    }

    // Class continues
}

Then in your ConfigureServices() method, you can use the following to declare your IConfiguration instance as a singleton service, which allows you to inject it and use it other classes.

services.AddSingleton(Configuration);

You actually do not need to specify your database connection string in your DbContext class since you have specified it in your service collection.

So in your Startup.cs, you would now do

services.AddDbContext<SQLiteTestDbContext>
    (options => options.UseSqlite(Configuration["ConnectionStrings:SQLiteTestConnection"]));

You may need to reference the following packages

  • Microsoft.Extensions.Configuration
  • Microsoft.Extensions.Configuration.FileExtensions
  • Microsoft.Extensions.Configuration.Json
Related