2

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.

brstkr
  • 1,423
  • 3
  • 18
  • 28
  • First, confirm that the ConfigurationManager.GetConnectionString["SQLiteTestConnection"].ConnectionString; is populating your connection string by putting a watch on it and debug breakpoint. If you confirm that it is pulling it, then it may be how you are initializing the Entity Framework DbContext. Please provide code snippets of both the Startup configuration where you have AddDbContext, and your class that inherits from Entity Framework DbContext. We need to see where you configured UseSqlite. – Stephen Raman May 31 '20 at 11:27
  • 1
    Does this answer your question? [Does ConfigurationManager work with ASP.NET core's appsettings.json?](https://stackoverflow.com/questions/52960856/does-configurationmanager-work-with-asp-net-cores-appsettings-json) – rph May 31 '20 at 11:36

1 Answers1

1

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
Matthew Trip
  • 326
  • 2
  • 15
  • Does the string in the [] of `Configuration[ConnectionStrings:SQLiteTestConnection]` need to be in "" ? I looked up into the definition before and saw something like string key. Thats why I am asking^^ will try it out in a second. Thanks :) – brstkr May 31 '20 at 13:15
  • Ah yes, it should be `Configuration["ConnectionStrings:SQLiteTestConnection"]`. My bad sorry. – Matthew Trip May 31 '20 at 13:34
  • Ok thanks it seems to be working. Just another question to get it understanded, what does the `services.AddSingleton(Configuration)` do? Can I use this Configuration then also in the Client Side Component of Blazor? Because I could not see any references between Client and Server. – brstkr May 31 '20 at 13:41
  • 1
    The `AddSingleton()` method adds the instance of whatever object you specify and its type into the service collection. This means that you can access this specified service from other classes using dependency injection. To be honest I do not know much about Blazor. It's best if you just try and see for yourself. – Matthew Trip May 31 '20 at 14:33