如何在创建appsettings.json
的 ASP.NET Core blazor WebAssembly Server 组件中设置连接字符串。
{
"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 正在使用中。 此数据库上下文存储在我的 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 类的数据库中创建了一些假数据。
在Startup.cs
类中,将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
实例声明为单一实例服务,这允许您注入它并将其用于其他类。
services.AddSingleton(Configuration);
实际上,您不需要在DbContext
类中指定数据库连接字符串,因为已在服务集合中指定了它。
所以在你的Startup.cs
,你现在会做
services.AddDbContext<SQLiteTestDbContext>
(options => options.UseSqlite(Configuration["ConnectionStrings:SQLiteTestConnection"]));
您可能需要参考以下软件包
- Microsoft.扩展.配置
- Microsoft.扩展名.配置.文件扩展名
- Microsoft.Extensions.Configuration.Json