I am using .NET Core 9, SQLite in my personal project. I can save into QueryHistory
table (row can be inserted into database). But when I invoke GetHistory()
, which accesses _context.QueryHistory
, I got this exception:
SQLite Error 14: ‘unable to open database file’.
at Microsoft.Data.Sqlite.SqliteException.ThrowExceptionForRC(Int32 rc, sqlite3 db)
at Microsoft.Data.Sqlite.SqliteConnectionInternal..ctor(SqliteConnectionStringBuilder connectionOptions, SqliteConnectionPool pool)
at Microsoft.Data.Sqlite.SqliteConnectionPool.GetConnection()
at Microsoft.Data.Sqlite.SqliteConnectionFactory.GetConnection(SqliteConnection outerConnection)
at Microsoft.Data.Sqlite.SqliteConnection.Open()
at System.Data.Common.DbConnection.OpenAsync(CancellationToken cancellationToken)
— End of stack trace from previous location —
at Microsoft.EntityFrameworkCore.Storage.RelationalConnection.OpenInternalAsync(Boolean errorsExpected, CancellationToken cancellationToken)
at Microsoft.EntityFrameworkCore.Storage.RelationalConnection.OpenInternalAsync(Boolean errorsExpected, CancellationToken cancellationToken)
at Microsoft.EntityFrameworkCore.Storage.RelationalConnectio
My code:
public class ExchangeDatabaseContext : DbContext
{
public required DbSet<QueryHistory> QueryHistory { get; set; }
public ExchangeDatabaseContext(DbContextOptions<ExchangeDatabaseContext> options) : base(options)
{
}
protected override void OnModelCreating(ModelBuilder modelBuilder)
{
modelBuilder.ApplyConfigurationsFromAssembly(typeof(ExchangeDatabaseContext).Assembly);
base.OnModelCreating(modelBuilder);
}
}
public class QueryHistoryRepository : IQueryHistoryRepository
{
protected readonly ExchangeDatabaseContext _context;
public QueryHistoryRepository(ExchangeDatabaseContext context)
{
this._context = context;
}
public async Task AddHistory(QueryHistory queryHistory)
{
await _context.AddAsync(queryHistory);
await _context.SaveChangesAsync();
}
public async Task<List<QueryHistory>> GetHistory()
{
var c = await _context.QueryHistory.ToListAsync();
return c;
}
}
// ------- in program.cs --------------
public static IServiceCollection AddPersistenceServices(this IServiceCollection services, IConfiguration configuration)
{
services.AddDbContext<ExchangeDatabaseContext>(options => {
options.UseSqlite(configuration.GetConnectionString("ConnectionString"));
// this line to suppress the warning when we Update-Database in nuget
options.ConfigureWarnings(warnings => warnings.Ignore(RelationalEventId.PendingModelChangesWarning));
});
services.AddScoped(typeof(IGenericRepository<>), typeof(GenericRepository<>));
services.AddScoped<IQueryHistoryRepository, QueryHistoryRepository>();
return services;
3