【发布时间】:2020-09-18 18:16:34
【问题描述】:
如何在我创建 appsettings.json 的 ASP.NET Core blazor WebAssembly 服务器组件中设置连接字符串。
{
"ConnectionStrings": {
"SQLiteTestConnection": "Data Source=./TestDB.db",
}
}
现在看起来像这样,但我无法通过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"));
}
...
我的 DbContext 正在使用中。 此 DbContext 存储在我的 Blazor Server 组件中
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 类的数据库中创建了一些假数据。
【问题讨论】:
-
首先,确认 ConfigurationManager.GetConnectionString["SQLiteTestConnection"].ConnectionString;正在通过对其进行监视并调试断点来填充您的连接字符串。如果您确认它正在拉动它,那么它可能是您初始化实体框架 DbContext 的方式。请提供您拥有 AddDbContext 的 Startup 配置以及从 Entity Framework DbContext 继承的类的代码 sn-ps。我们需要看看你在哪里配置了 UseSqlite。
标签: c# sqlite entity-framework-core database-connection connection-string