【问题标题】:Filter expression cannot be specified for an entity type because it may only be applied to the root entity type in a hierarchy无法为实体类型指定过滤器表达式,因为它只能应用于层次结构中的根实体类型
【发布时间】:2018-05-22 21:03:39
【问题描述】:

我正在尝试更改 asp.net 生成其身份表的方式,尝试将生成基于 int 的 Id 而不是 Guid(string),还添加不同的模式(而不是 dbo -> Security) 和为我的所有实体创建一个 QueryFilter,在这种情况下,我为每个类创建了一个 Mapping,但只会用一个给我错误的东西来说明这个想法。

public class AspNetRole : IdentityRole<int>, IEntityBase
{
    public bool IsDeleted { get; set; }
    public string CreatedBy { get; set; }
    public string UpdatedBy { get; set; }
    public DateTime? CreatedOn { get; set; }
    public DateTime? UpdatedOn { get; set; }
}

 public interface IEntityBase
 {
    int Id { get; set; }
    bool IsDeleted { get; set; }
    string CreatedBy { get; set; }
    string UpdatedBy { get; set; }
    DateTime? CreatedOn { get; set; }
    DateTime? UpdatedOn { get; set; }
 }

带有 QueryFilter 的映射类:

public class AspNetRoleMap : IEntityTypeConfiguration<AspNetRole>
{
    public void Configure(EntityTypeBuilder<AspNetRole> builder)
    {
        builder.ToTable(name: "AspNetRole", schema: "Security");
        builder.HasQueryFilter(app => !app.IsDeleted);
    }
}

DbContext:

public class AspNetSecurityDbContext : IdentityDbContext<AspNetUser, IdentityRole<int>, int>
    {
        public AspNetSecurityDbContext(DbContextOptions<AspNetSecurityDbContext> options)
            : base(options)
        {
        }

        protected override void OnModelCreating(ModelBuilder builder)
        {
            base.OnModelCreating(builder);

            builder.ApplyConfiguration(new AspNetRoleMap());
        }
    }

运行迁移后,我收到以下错误:

无法指定过滤表达式'app => Not(app.IsDeleted)' 对于实体类型“AspNetRole”。过滤器只能应用于根 层次结构中的实体类型。

我尝试了这种方法https://github.com/aspnet/EntityFrameworkCore/issues/10259,但仍然遇到更多错误

builder.HasQueryFilter(app => !((IEntityBase)app).IsDeleted);

【问题讨论】:

    标签: asp.net-core entity-framework-core asp.net-core-identity


    【解决方案1】:

    该问题与 EF Core 查询过滤器没有任何共同之处,而是不正确的基本通用 IdentityDbContext 参数。这里

    : IdentityDbContext<AspNetUser, IdentityRole<int>, int>
    

    您正在传递IdentityRole&lt;int&gt;,它在基础OnModelCreating 中将被配置为实体,因此EF Core 将使用TPH inheritance strategy 映射您的AspNetRole 实体,它与附加的discriminator 列引入了额外的约束,例如您得到的查询过滤器异常。

    要解决这个问题,请传递正确的泛型类型参数,在这种情况下是自定义 AspNetRole 类:

    : IdentityDbContext<AspNetUser, AspNetRole, int>
    

    如果您创建其他自定义实体继承泛型 IndentityXyz&lt;&gt; 类,请查看具有更多泛型类型参数的其他基本 IdentityDbContext 类,并选择允许您传递所有自定义标识派生类型的类.

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2018-03-09
      • 2021-07-05
      • 1970-01-01
      • 2010-11-24
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多