我的控制臺專案中有一個 SQLite 資料庫,并且此連接字串在 DbContext 設定中作業正常:
protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
{
optionsBuilder.UseSqlite("Data Source=PubDatabase.db")
當我編譯時,資料庫是在 ConsoleApp>bin>debug>net6.0>PubDatabase.db 中創建的。在我的 ASP.NET Core 專案中,我使用 appsettings.json 設定連接字串:
"ConnectionStrings": {
"PubConnection": "Data Source=../PubDatabase.db"
我將 PubDatabase.db 檔案放在此檔案夾中:APIProject>bin>debug>net6.0。
在 Program.cs 我使用:
builder.Services.AddDbContext<PubContext>(
opt=>opt.UseSqlite(builder.Configuration.GetConnectionString("PubConnection"))
我的 DbContext :
namespace PublisherData;
public class PubContext:DbContext
{
public DbSet<Author> Authors { get; set; }
public DbSet<Book> Books { get; set; }
public DbSet<Artist> Artists { get; set; }
public DbSet<Cover> Covers { get; set; }
public PubContext(DbContextOptions<PubContext> options)
:base(options)
{
}
但是當我在 AuthorsController 中嘗試這個時:
[Route("api/[controller]")]
[ApiController]
public class AuthorsController : ControllerBase
{
private readonly PubContext _context;
public AuthorsController(PubContext context)
{
_context = context;
}
// GET: api/Authors
[HttpGet]
public async Task<ActionResult<IEnumerable<Author>>> GetAuthors()
{
return await _context.Authors.ToListAsync();
}
我收到此錯誤:

我應該將資料庫放在哪里才能使用連接字串訪問它?
uj5u.com熱心網友回復:
我做了一個簡單的測驗,你可以按照我下面的步驟。
首先,安裝 NuGet 包:
Microsoft.EntityFrameworkCore.Design
Microsoft.EntityFrameworkCore.Sqlite
Microsoft.EntityFrameworkCore.Tools
然后,創建背景關系:
public class SqlContext : DbContext
{
public SqlContext(DbContextOptions<SqlContext> Options) : base(Options)
{
}
public DbSet<Author> Authors { get; set; }
}
添加連接字串:
appsettings.json:
"ConnectionStrings": {
"WebApiDatabase": "Data Source=PubDatabase.db"
}
程式.cs:
builder.Services.AddEntityFrameworkSqlite().AddDbContext<SqlContext>(opt => opt.UseSqlite(builder.Configuration.GetConnectionString("WebApiDatabase")));
最后,遷移和更新資料庫:
Add-Migration InitialCreate
Update-Database
三個檔案出現在目錄結構中:

測驗結果:

希望這可以幫到你。
轉載請註明出處,本文鏈接:https://www.uj5u.com/qukuanlian/514720.html
標籤:sqliteasp.net-core-webapief-core-6.0
上一篇:每年所有月份的年度總計
下一篇:從sql中的計數中選擇最大值
