7

I am having trouble with this error when Adding new migration. The filter expression 'e => Not(e.IsDeleted)' cannot be specified for entity type 'Babysitter'. A filter may only be applied to the root entity type in a hierarchy.

What I am doing is that I have 2 classes Babysitter and Parent that both need to be ApplicationUsers, because they have different properties. So I made them inherit the ApplicationUser class and extended them.

This is the ApplicationUser class.

public class ApplicationUser : IdentityUser, IAuditInfo, IDeletableEntity
{
    public ApplicationUser()
    {
        this.Id = Guid.NewGuid().ToString();
        this.Roles = new HashSet<IdentityUserRole<string>>();
        this.Claims = new HashSet<IdentityUserClaim<string>>();
        this.Logins = new HashSet<IdentityUserLogin<string>>();
    }

    // Audit info
    public DateTime CreatedOn { get; set; }

    public DateTime? ModifiedOn { get; set; }

    // Deletable entity
    public bool IsDeleted { get; set; }

    public DateTime? DeletedOn { get; set; }

    public virtual ICollection<IdentityUserRole<string>> Roles { get; set; }

    public virtual ICollection<IdentityUserClaim<string>> Claims { get; set; }

    public virtual ICollection<IdentityUserLogin<string>> Logins { get; set; }
}

These are the Babysitter and Parent classes.

public class Babysitter : ApplicationUser
{
    public Babysitter()
    {
        this.Appointments = new HashSet<Appointment>();
        this.Comments = new HashSet<Comment>();
    }

    public string Name { get; set; }

    public int Age { get; set; }

    public Gender Gender { get; set; }

    public DateTime DateOfBirth { get; set; }

    public string ImageUrl { get; set; }

    public string Description { get; set; }

    public decimal WageRate { get; set; }

    public string Address { get; set; }

    public decimal Rating { get; set; }

    public ICollection<Comment> Comments { get; set; }

    public ICollection<Appointment> Appointments { get; set; }
}



public class Parent : ApplicationUser
{
    public Parent()
    {
        this.Comments = new HashSet<Comment>();
        this.Kids = new HashSet<Kid>();
        this.Appointments = new HashSet<Appointment>();
    }

    public string Name { get; set; }

    public string ImageUrl { get; set; }

    public decimal Rating { get; set; }

    public string Address { get; set; }

    public ICollection<Comment> Comments { get; set; }

    public ICollection<Kid> Kids { get; set; }

    public ICollection<Appointment> Appointments { get; set; }
}

And so when I try to Add-Migration Initial I get this error: The filter expression 'e => Not(e.IsDeleted)' cannot be specified for entity type 'Babysitter'. A filter may only be applied to the root entity type in a hierarchy.

This is the ApplicationDbContext.cs

public class ApplicationDbContext : IdentityDbContext<ApplicationUser, ApplicationRole, string>
{
    private static readonly MethodInfo SetIsDeletedQueryFilterMethod =
        typeof(ApplicationDbContext).GetMethod(
            nameof(SetIsDeletedQueryFilter),
            BindingFlags.NonPublic | BindingFlags.Static);

    public ApplicationDbContext(DbContextOptions<ApplicationDbContext> options)
        : base(options)
    {
    }

    public DbSet<Babysitter> Babysitters{ get; set; }

    public DbSet<Parent> Parents { get; set; }

    public DbSet<Comment> Comments { get; set; }

    public DbSet<Kid> Kids{ get; set; }

    public DbSet<Appointment> Appointments { get; set; }

    public DbSet<Setting> Settings { get; set; }

    public override int SaveChanges() => this.SaveChanges(true);

    public override int SaveChanges(bool acceptAllChangesOnSuccess)
    {
        this.ApplyAuditInfoRules();
        return base.SaveChanges(acceptAllChangesOnSuccess);
    }

    public override Task<int> SaveChangesAsync(CancellationToken cancellationToken = default) =>
        this.SaveChangesAsync(true, cancellationToken);

    public override Task<int> SaveChangesAsync(
        bool acceptAllChangesOnSuccess,
        CancellationToken cancellationToken = default)
    {
        this.ApplyAuditInfoRules();
        return base.SaveChangesAsync(acceptAllChangesOnSuccess, cancellationToken);
    }

    protected override void OnModelCreating(ModelBuilder builder)
    {
        // Needed for Identity models configuration
        base.OnModelCreating(builder);

        ConfigureUserIdentityRelations(builder);

        EntityIndexesConfiguration.Configure(builder);

        var entityTypes = builder.Model.GetEntityTypes().ToList();

        // Set global query filter for not deleted entities only
        var deletableEntityTypes = entityTypes
            .Where(et => et.ClrType != null && typeof(IDeletableEntity).IsAssignableFrom(et.ClrType));
        foreach (var deletableEntityType in deletableEntityTypes)
        {
            var method = SetIsDeletedQueryFilterMethod.MakeGenericMethod(deletableEntityType.ClrType);
            method.Invoke(null, new object[] { builder });
        }

        // Disable cascade delete
        var foreignKeys = entityTypes
            .SelectMany(e => e.GetForeignKeys().Where(f => f.DeleteBehavior == DeleteBehavior.Cascade));
        foreach (var foreignKey in foreignKeys)
        {
            foreignKey.DeleteBehavior = DeleteBehavior.Restrict;
        }
    }

    private static void ConfigureUserIdentityRelations(ModelBuilder builder)
    {
        builder.Entity<ApplicationUser>()
            .HasMany(e => e.Claims)
            .WithOne()
            .HasForeignKey(e => e.UserId)
            .IsRequired()
            .OnDelete(DeleteBehavior.Restrict);

        builder.Entity<ApplicationUser>()
            .HasMany(e => e.Logins)
            .WithOne()
            .HasForeignKey(e => e.UserId)
            .IsRequired()
            .OnDelete(DeleteBehavior.Restrict);

        builder.Entity<ApplicationUser>()
            .HasMany(e => e.Roles)
            .WithOne()
            .HasForeignKey(e => e.UserId)
            .IsRequired()
            .OnDelete(DeleteBehavior.Restrict);
    }

    private static void SetIsDeletedQueryFilter<T>(ModelBuilder builder)
        where T : class, IDeletableEntity
    {
        builder.Entity<T>().HasQueryFilter(e => !e.IsDeleted);
    }

    private void ApplyAuditInfoRules()
    {
        var changedEntries = this.ChangeTracker
            .Entries()
            .Where(e =>
                e.Entity is IAuditInfo &&
                (e.State == EntityState.Added || e.State == EntityState.Modified));

        foreach (var entry in changedEntries)
        {
            var entity = (IAuditInfo)entry.Entity;
            if (entry.State == EntityState.Added && entity.CreatedOn == default)
            {
                entity.CreatedOn = DateTime.UtcNow;
            }
            else
            {
                entity.ModifiedOn = DateTime.UtcNow;
            }
        }
    }
}

1 Answer 1

6

So you're trying to add your filter by convention;

        // Set global query filter for not deleted entities only
        var deletableEntityTypes = entityTypes
            .Where(et => et.ClrType != null && typeof(IDeletableEntity).IsAssignableFrom(et.ClrType));
        foreach (var deletableEntityType in deletableEntityTypes)
        {
            var method = SetIsDeletedQueryFilterMethod.MakeGenericMethod(deletableEntityType.ClrType);
            method.Invoke(null, new object[] { builder });
        }

But that is matching against all three types; Babysitter, Parent, ApplicationUser. The error message is telling you that in a table hierarchy, only apply filters to base types;

    .Where(et => et.ClrType != null 
        && typeof(IDeletableEntity).IsAssignableFrom(et.ClrType)
        && et.BaseType == null)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.