using Microsoft.EntityFrameworkCore; namespace ZymonicServices; public class ZymonicDbContext : DbContext, IZymonicDbContext { public ZymonicDbContext(DbContextOptions options) : base(options) { StartupTasks(); } public void StartupTasks() { this.Database.EnsureCreated(); // TODO-Phase2 Add in something (DbUp?) to automatically update the SQLite DB } protected override void OnModelCreating(ModelBuilder modelBuilder) { // TODO-Phase2 automatically load assemblies https://www.davidguida.net/how-to-find-all-application-assemblies // https://romiller.com/2012/03/26/dynamically-building-a-model-with-code-first/ var entityMethod = typeof(ModelBuilder) .GetMethods() .Where(x => x.Name == "Entity") .Where(x => x.IsGenericMethod) .FirstOrDefault(); if(entityMethod is null) { throw new Exception("Entity method cannot be located - check EFCore properly installed."); } foreach (var assembly in AppDomain.CurrentDomain.GetAssemblies()) { var entityTypes = assembly .GetTypes() .Where(t => t.GetCustomAttributes(typeof(ZymonicLocalDbSetAttribute), inherit: true) .Any()); foreach (var type in entityTypes) { entityMethod.MakeGenericMethod(type) .Invoke(modelBuilder, new object[] { }); } } base.OnModelCreating(modelBuilder); } public Task SaveChangesAsync() { return base.SaveChangesAsync(); } public override int SaveChanges() { return base.SaveChanges(); } }