簡體   English   中英

如何在 appsettings.json 中設置連接字符串?

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

如何在我的 ASP.NET Core blazor WebAssembly Server 組件中設置連接字符串,我在其中創建了appsettings.json

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

現在它看起來像這樣,但我無法通過Update-Database創建數據庫。

啟動.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"));
        }
...

我的 DbContext 正在使用中。 這個 DbContext 存儲在我的 Blazor 服務器組件中

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

我還在 DbContext Class 的數據庫中創建了一些假數據。

在您的Startup.cs class 中,將IConfiguration的實例聲明為字段並在構造函數中對其進行初始化。

public class Startup
{
    private IConfiguration Configuration { get; }

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

        Configuration = configurationBuilder.Build();
    }

    // Class continues
}

然后在您的ConfigureServices()方法中,您可以使用以下內容將您的IConfiguration實例聲明為 singleton 服務,這允許您注入它並在其他類中使用它。

services.AddSingleton(Configuration);

您實際上不需要在DbContext class 中指定數據庫連接字符串,因為您已在服務集合中指定了它。

所以在你的Startup.cs中,你現在會做

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

您可能需要參考以下軟件包

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM