56 lines
1.6 KiB
C#
56 lines
1.6 KiB
C#
using Microsoft.EntityFrameworkCore;
|
|
using UtopiaCanteenSystem.Models;
|
|
using System.IO;
|
|
|
|
namespace UtopiaCanteenSystem.Data;
|
|
|
|
/// <summary>
|
|
/// SQLite DbContext for Labour and ScanRecord tables.
|
|
/// Database file is created in application directory on first run.
|
|
/// </summary>
|
|
public class AppDbContext : DbContext
|
|
{
|
|
private static readonly string DbPath = Path.Combine(
|
|
AppDomain.CurrentDomain.BaseDirectory,
|
|
"utopia_canteen.db");
|
|
|
|
public DbSet<Labour> Labour { get; set; }
|
|
public DbSet<ScanRecord> ScanRecords { get; set; }
|
|
|
|
public AppDbContext() { }
|
|
|
|
public AppDbContext(DbContextOptions<AppDbContext> 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<Labour>(e =>
|
|
{
|
|
e.HasKey(x => x.Id);
|
|
e.HasIndex(x => x.CardId);
|
|
});
|
|
|
|
// ScanRecord: Index for unsynced queries and by ScanTime.
|
|
modelBuilder.Entity<ScanRecord>(e =>
|
|
{
|
|
e.HasKey(x => x.Id);
|
|
e.HasIndex(x => x.IsSynced);
|
|
e.HasIndex(x => x.ScanTime);
|
|
});
|
|
}
|
|
|
|
/// <summary>
|
|
/// Ensures database exists and is migrated. Call on app startup.
|
|
/// </summary>
|
|
public void EnsureDatabaseCreated()
|
|
{
|
|
Database.EnsureCreated();
|
|
}
|
|
}
|