小编典典

筛选所有查询(尝试实现软删除)

c#

我试图在EF Core 2.0中开始软删除行为。

public interface ISoftDeleteModel
{
    bool IsDeleted { get; set; }
}

创建适当的列和软删除可以正常工作,但不能从DbContext过滤实体。

我想在上下文中使用查询过滤,但遇到问题。

protected override void OnModelCreating(ModelBuilder modelBuilder)
{
    Type entityType;
    // ^^^ it contains type of entity, eg. Blog, Post, etc. using
    // modelBuilder.Model.GetEntityTypes().First().Name and converting to Type

    var entity = modelBuilder.Entity(entityType);
    if(entityType.GetInterface("ISoftDeleteModel") != null)
    {
        // ??? how to access IsDeleted property ???
        entity.HasQueryFilter(x => !x.IsDeleted);
    }
}

问题很简单-如何访问IsDeleted属性?

如果我知道实体的类型,例如 发布并发布实现的ISoftDeleteModel,我将能够做到这一点:

protected override void OnModelCreating(ModelBuilder modelBuilder)
{
    modelBuilder.Entity<Post>().HasQueryFilter(x => !x.IsDeleted);
}

但是我不知道类型。我正在尝试实现简单的事情-实现该接口的所有模型都将被自动过滤。我想念什么吗?


阅读 598

收藏
2020-05-19

共1个答案

小编典典

无法测试确切的API,但是一般的方法是创建一个受约束的泛型方法并通过反射进行调用:

public static class EFFilterExtensions
{
    public static void SetSoftDeleteFilter(this ModelBuilder modelBuilder, Type entityType)
    {
        SetSoftDeleteFilterMethod.MakeGenericMethod(entityType)
            .Invoke(null, new object[] { modelBuilder });
    }

    static readonly MethodInfo SetSoftDeleteFilterMethod = typeof(EFFilterExtensions)
               .GetMethods(BindingFlags.Public | BindingFlags.Static)
               .Single(t => t.IsGenericMethod && t.Name == "SetSoftDeleteFilter");

    public static void SetSoftDeleteFilter<TEntity>(this ModelBuilder modelBuilder) 
        where TEntity : class, ISoftDeleteModel
    {
        modelBuilder.Entity<TEntity>().HasQueryFilter(x => !x.IsDeleted);
    }
}

现在,您可以在您的内部使用类似的内容OnModelCreating

foreach (var type in modelBuilder.Model.GetEntityTypes())
{
    if (typeof(ISoftDeleteModel).IsAssignableFrom(type.ClrType))
        modelBuilder.SetSoftDeleteFilter(type.ClrType);
}
2020-05-19