不能为实体类型指定过滤器表达式.过滤器只能应用于层次结构中的根实体类型 [英] The filter expression cannot be specified for entity type. A filter may only be applied to the root entity type in a hierarchy

查看:120
本文介绍了不能为实体类型指定过滤器表达式.过滤器只能应用于层次结构中的根实体类型的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

添加新迁移时,我遇到此错误.不能为实体类型"Babysitter"指定过滤表达式"e => Not(e.IsDeleted)".过滤器只能应用于层次结构中的根实体类型.

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.

我正在做的是,我有两个类Babysitter和Parent,它们都必须是ApplicationUsers,因为它们具有不同的属性.因此,我让它们继承了ApplicationUser类并对其进行了扩展.

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.

这是ApplicationUser类.

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; }
}

因此,当我尝试添加初始迁移时,会出现以下错误:不能为实体类型"Babysitter"指定过滤器表达式"e => Not(e.IsDeleted)".过滤器只能应用于层次结构中的根实体类型.

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.

这是ApplicationDbContext.cs

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;
            }
        }
    }
}

推荐答案

因此,您尝试按约定添加过滤器;

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 });
        }

但这与所有三种类型都匹配;保姆父母 ApplicationUser .错误消息告诉您,在表层次结构中,仅将过滤器应用于基本类型;

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)

这篇关于不能为实体类型指定过滤器表达式.过滤器只能应用于层次结构中的根实体类型的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆