using Microsoft.EntityFrameworkCore; using Microsoft.EntityFrameworkCore.Query; using System; using System.Collections.Generic; using System.Linq; using System.Linq.Expressions; using System.Text; using YABA.Models; using YABA.Models.Interfaces; namespace YABA.Data.Context { public class YABABaseContext : DbContext { public YABABaseContext(DbContextOptions options) : base(options) { } protected override void OnModelCreating(ModelBuilder modelBuilder) { // Add lookup backed data here // SAMPLE // var lookupBackedData = Enum.GetValues(typeof(LookupEnum)).Cast(); // modelBuilder.Entity().HasData(lookupBackedData.Select(x => new LookupModel(x))); modelBuilder.Model.GetEntityTypes() .Where(entityType => typeof(ISoftDeletable).IsAssignableFrom(entityType.ClrType)) .ToList() .ForEach(entityType => { modelBuilder.Entity(entityType.ClrType) .HasQueryFilter(ConvertFilterExpression(e => !e.IsDeleted, entityType.ClrType)); }); modelBuilder.Entity() .HasKey(x => new { x.BookmarkId, x.TagId }); modelBuilder.Entity() .HasIndex(x => x.Auth0Id) .IsUnique(); modelBuilder.Entity() .HasIndex(x => new { x.Name, x.UserId }) .IsUnique(); modelBuilder.Entity() .HasIndex(x => new { x.Url, x.UserId }) .IsUnique(); } public DbSet Bookmarks { get; set; } public DbSet Tags { get; set; } public DbSet BookmarkTags { get; set; } public DbSet Users { get; set; } private static LambdaExpression ConvertFilterExpression( Expression> filterExpression, Type entityType) { // SOURCE: https://stackoverflow.com/questions/47673524/ef-core-soft-delete-with-shadow-properties-and-query-filters/48744644#48744644 var newParam = Expression.Parameter(entityType); var newBody = ReplacingExpressionVisitor.Replace(filterExpression.Parameters.Single(), newParam, filterExpression.Body); return Expression.Lambda(newBody, newParam); } } }