Basics setup, going to change how repos work
This commit is contained in:
69
DBConnection/AppDbContext.cs
Normal file
69
DBConnection/AppDbContext.cs
Normal file
@@ -0,0 +1,69 @@
|
||||
using System.Reflection;
|
||||
using DBConnection.Interfaces;
|
||||
using DBConnection.ModelBuilders;
|
||||
using DBConnection.Models;
|
||||
using DBConnection.Seeders;
|
||||
using Microsoft.EntityFrameworkCore;
|
||||
|
||||
namespace DBConnection;
|
||||
|
||||
public class AppDbContext : DbContext
|
||||
{
|
||||
public DbSet<Novel> Novels { get; set; }
|
||||
public DbSet<Chapter> Chapters { get; set; }
|
||||
public DbSet<Author> Authors { get; set; }
|
||||
public DbSet<User> Users { get; set; }
|
||||
public DbSet<Tag> Tags { get; set; }
|
||||
public DbSet<UserNovel> UserNovels { get; set; }
|
||||
|
||||
private readonly IEnumerable<ISeeder> _seeders =
|
||||
from t in Assembly.GetExecutingAssembly().GetTypes()
|
||||
where t.IsClass && t.Namespace.Contains(nameof(DBConnection.Seeders)) && typeof(ISeeder).IsAssignableFrom(t)
|
||||
select (ISeeder) Activator.CreateInstance(t);
|
||||
|
||||
private static readonly IEnumerable<IModelBuilder> ModelBuilders =
|
||||
from t in Assembly.GetExecutingAssembly().GetTypes()
|
||||
where t.IsClass && t.Namespace.Contains(nameof(DBConnection.ModelBuilders)) && typeof(IModelBuilder).IsAssignableFrom(t)
|
||||
select (IModelBuilder) Activator.CreateInstance(t);
|
||||
|
||||
public AppDbContext(DbContextOptions options) : base(options)
|
||||
{
|
||||
}
|
||||
|
||||
public override Task<int> SaveChangesAsync(CancellationToken cancellationToken = new CancellationToken())
|
||||
{
|
||||
UpdateAuditInfo();
|
||||
return base.SaveChangesAsync(cancellationToken);
|
||||
}
|
||||
|
||||
private void UpdateAuditInfo()
|
||||
{
|
||||
var entries = ChangeTracker.Entries().Where(x =>
|
||||
x.Entity is BaseEntity && (x.State == EntityState.Added || x.State == EntityState.Modified));
|
||||
foreach(var entry in entries) {
|
||||
if (entry.State == EntityState.Added)
|
||||
{
|
||||
((BaseEntity)entry.Entity).DateCreated = DateTime.Now;
|
||||
}
|
||||
((BaseEntity)entry.Entity).DateModified = DateTime.Now;
|
||||
}
|
||||
}
|
||||
|
||||
protected override void OnModelCreating(ModelBuilder modelBuilder)
|
||||
{
|
||||
base.OnModelCreating(modelBuilder);
|
||||
foreach (var builder in ModelBuilders)
|
||||
{
|
||||
builder.BuildModel(modelBuilder);
|
||||
}
|
||||
foreach (var seeder in _seeders)
|
||||
{
|
||||
seeder.SeedData(modelBuilder);
|
||||
}
|
||||
}
|
||||
|
||||
protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
|
||||
{
|
||||
base.OnConfiguring(optionsBuilder);
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user