using Microsoft.EntityFrameworkCore; using System; using System.Linq; using System.Reflection; using Domain; using Domain.Identity; using Infrastructure; using Domain.BaseData; namespace Core.Db { public class PanakDbContext : DbContext { public PanakDbContext(DbContextOptions options) : base(options) { } public DbSet Accounts { get; set; } public DbSet Roles { get; set; } public DbSet AccountRoles { get; set; } public DbSet LoginTokens { get; set; } public DbSet RefreshTokens { get; set; } #region ThisProject public DbSet Plants { get; set; } #endregion protected override void OnModelCreating(ModelBuilder modelBuilder) { modelBuilder.Entity() .HasOne(x => x.RefreshToken) .WithOne(a => a.LoginToken) .HasForeignKey(x => x.LoginTokenId); modelBuilder.Entity().HasData( new Role { Name = Consts.AdminRole }, new Role { Name = Consts.Developer } ); base.OnModelCreating(modelBuilder); } protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder) { optionsBuilder.UseLazyLoadingProxies(); base.OnConfiguring(optionsBuilder); } } public static class EFFilterExtensions { public static void ApplySoftDeleteFilter(this ModelBuilder modelBuilder, Type entityType) { SetSoftDeleteFilterMethod.MakeGenericMethod(entityType).Invoke(null, new object[] { modelBuilder }); } static readonly MethodInfo SetSoftDeleteFilterMethod = typeof(EFFilterExtensions) .GetMethods(BindingFlags.Public | BindingFlags.Static) .Single(t => t.IsGenericMethod && t.Name == "ApplySoftDeleteFilter"); public static void ApplySoftDeleteFilter(this ModelBuilder modelBuilder) where TEntity : BaseEntity { modelBuilder.Entity().HasQueryFilter(x => !x.Deleted); } } }