无法为实体类型指定过滤器表达式,因为它只能应用于层次结构中的根实体类型

时间:2018-05-22 21:03:39

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

我正在尝试改变asp.net生成其身份表的方式,尝试将生成基于int而不是Guid(字符串),同时添加不同的模式(而不是dbo - >安全性)我的所有实体都有一个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 =&gt;不能(app.IsDeleted)'不能指定   对于实体类型'AspNetRole'。过滤器只能应用于根   层次结构中的实体类型。

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

builder.HasQueryFilter(app =&gt;!((IEntityBase)app).IsDeleted);

1 个答案:

答案 0 :(得分:4)

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

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

您正在传递IdentityRole<int>,其基础OnModelCreating将配置为实体,因此EF Core将使用{{3}映射您的AspNetRole实体与附加的鉴别器列一起引入了额外的约束,比如你得到的查询过滤器异常。

要解决此问题,请传递正确的泛型类型参数,在本例中为自定义AspNetRole类:

: IdentityDbContext<AspNetUser, AspNetRole, int>

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