ASP.NET Core配置Builder无法连接SQLite数据库问题求助
SQLite连接无反应问题排查与解决
问题描述
我尝试连接SQLite数据库,已在appsettings.json中配置好连接字符串,但调用AddDbContext注册服务时,程序既不报错也无日志输出,仿佛上下文未被正确加载。使用.NET 7版本,已验证SQLite文件无异常访问限制,连接字符串也检查无误。
相关代码
AppDbContext.cs
public class AppDbContext : DbContext { public AppDbContext(DbContextOptions<AppDbContext> options) : base(options) { } }
Program.cs
using Microsoft.EntityFrameworkCore; using Portfolio_Blog.Data; //using Microsoft.Extensions.Logging; var builder = WebApplication.CreateBuilder(args); // Create a logger var loggerFactory = LoggerFactory.Create(builder => builder.AddConsole()); var logger = loggerFactory.CreateLogger("MyApplication"); // Configure services builder.Services.AddRazorPages(); builder.Services.AddServerSideBlazor(); // Log a message logger.LogInformation("Connection string setup point reached"); builder.Services.AddDbContext<AppDbContext>(options => { var configuration = builder.Configuration; options.UseSqlite(configuration.GetConnectionString("DefaultConnection")); if (options.IsConfigured) { logger.LogInformation("Connected to the database."); } else { logger.LogError("Failed to connect to the database."); } }); var app = builder.Build(); if (!app.Environment.IsDevelopment()) { app.UseHsts(); } app.UseHttpsRedirection(); app.UseStaticFiles(); app.UseRouting(); app.MapBlazorHub(); app.MapFallbackToPage("/_Host"); // Configure the database context using the connection string app.Run();
最终解决方案
经过排查,发现问题根源是项目类型不匹配。将原Server-Side Blazor项目切换为ASP.NET Web API项目后,数据库连接、上下文注册均恢复正常,日志也能正常输出。
内容的提问来源于stack exchange,提问作者Eternan0
相关产品推荐
相关产品推荐

