在调用IgnoreQueryFilters之后,如何在EntityFramework Core中再次启用QueryFilters?

时间:2018-02-15 23:27:40

标签: c# entity-framework entity-framework-core

以下是我的内容,一个Application个实例包含两个Tags,一个标记为IsDeleted,另一个未标记为Application。我的TagIsDeleted类在模型上都有public class Application { public int Id { get; set; } public bool IsDeleted { get; set; } public ICollection<Tag> Tags { get; set; } = new List<Tag>(); } 属性。

ApplicationConfiguration

我的public class ApplicationConfiguration : IEntityTypeConfiguration<Application> { public void Configure(EntityTypeBuilder<Application> builder) { builder.ToTable("Application"); builder.HasQueryFilter(d => !d.IsDeleted); builder.HasKey(d => d.Id); builder.Property(d => d.Id).ValueGeneratedOnAdd(); builder.HasQueryFilter(d => !d.IsDeleted); } } 看起来像这样

IsDeleted

正如您所见,查询过滤器已应用于Document。对于Tagbuilder.HasQueryFilter(d => !d.IsDeleted); ,我应用了相同的查询过滤器

GetAll

在我的存储库中,我有一个public virtual IQueryable<TEntity> GetAll(string[] include, bool includeAllRecords = false) { IQueryable<TEntity> query = includeAllRecords ? Context.Set<TEntity>().IgnoreQueryFilters() : Context.Set<TEntity>(); if (include != null) { query = include.Aggregate(query, (current, includePath) => current.Include(includePath)); } return query; } 方法,看起来像这样

IgnoreQueryFilters

当我传递布尔参数时,请参阅ApplicationRepository。现在我可以对var appsWithJustActiveTags = ApplicationRepository.GetAll(new[] { "Tags" }).ToList(); var allTags = ApplicationRepository.GetAll(new[] { "Tags" }, true).ToList();

进行查询
var allTags = ApplicationRepository.GetAll(new[] { "Tags" }, true).ToList();
var appsWithJustActiveTags = ApplicationRepository.GetAll(new[] { "Tags" }).ToList();

当我传递布尔参数时,两个查询都返回正确的标记值,在第一个查询中,我使用未删除的标记获取应用程序,在第二个查询中,我得到包含所有标记的相同应用程序删除了一个。但是,如果我更改此查询的执行顺序,则两者都返回相同的结果

Context.Set<TEntity>().IgnoreQueryFilters();

似乎EntityFramework Core会在同一个上下文中为所有查询禁用QueryFilters,如果您调用Context.Set<TEntity>();,并且对简单display: -webkit-box; display: -moz-box; display: -ms-flexbox; display: -webkit-flex; display: flex; 的任何后续调用都不会再次返回过滤器

1 个答案:

答案 0 :(得分:1)

您可以对此类型的进展使用非跟踪查询。

她是这个的链接。 https://docs.microsoft.com/en-us/ef/core/querying/tracking

一个简单的用法,你可能需要添加一些东西。我没有调试这段代码。

<强> GetAllWithoutFilter

Context.Set&LT;的 TEntity &GT;()的 AsNoTracking ()IgnoreQueryFilters();

<强> GetAllAsNoTracking

Context.Set&LT;的 TEntity &GT;();

public virtual IQueryable<TEntity> GetAllWithoutFilter(string[] include)
{
    IQueryable<TEntity> query = Context.Set<TEntity>().AsNoTracking().IgnoreQueryFilters();

    if (include != null)
    {
        query = include.Aggregate(query, (current, includePath) => current.Include(includePath));
    }

    return query;
}


public virtual IQueryable<TEntity> GetAll(string[] include)
{
    IQueryable<TEntity> query =  Context.Set<TEntity>();

    if (include != null)
    {
        query = include.Aggregate(query, (current, includePath) => current.Include(includePath));
    }

    return query;
}