using Microsoft.EntityFrameworkCore;
using UtopiaCanteenSystem.Models;
using System.IO;
namespace UtopiaCanteenSystem.Data;
///
/// SQLite DbContext for Labour and ScanRecord tables.
/// Database file is created in application directory on first run.
///
public class AppDbContext : DbContext
{
private static readonly string DbPath = Path.Combine(
AppDomain.CurrentDomain.BaseDirectory,
"utopia_canteen.db");
public DbSet Labour { get; set; }
public DbSet ScanRecords { get; set; }
public AppDbContext() { }
public AppDbContext(DbContextOptions options) : base(options) { }
protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
{
if (!optionsBuilder.IsConfigured)
optionsBuilder.UseSqlite($"Data Source={DbPath}");
}
protected override void OnModelCreating(ModelBuilder modelBuilder)
{
// Labour: CardId should be indexed for lookups.
modelBuilder.Entity(e =>
{
e.HasKey(x => x.Id);
e.HasIndex(x => x.CardId);
});
// ScanRecord: Index for unsynced queries and by ScanTime.
modelBuilder.Entity(e =>
{
e.HasKey(x => x.Id);
e.HasIndex(x => x.IsSynced);
e.HasIndex(x => x.ScanTime);
});
}
///
/// Ensures database exists and is migrated. Call on app startup.
///
public void EnsureDatabaseCreated()
{
Database.EnsureCreated();
}
}