禁用导航属性的软删除查询过滤器

4
我使用 Ef Core 2.1,启用了软删除查询过滤器。在某些情况下,我想从实体中检索已软删除的导航属性,但无法检索数据(导航属性为空,因为它已被软删除)。我使用了这个 doc(编写于2017年)作为参考,其中指出:
“过滤器不能包含对导航属性的引用。”
我希望知道是否有任何方法可以启用这种行为。
public class Form {

    public int Id { get; set; }

    public virtual Sprint Sprint {get; set;}
}

public class Sprint: ISoftDeleteable {

    public int Id { get; set; }

    public string Name {get; set;}
}

// Indicates that every model that implements this interface should use soft delete.
public interface ISoftDeleteable
{ 

}

 // Both statements have returned null.
 Sprint sprint = applicationDbContext.Forms.FirstOrDefault(f => f.Id == 1).Sprint;
 Sprint sprint = applicationDbContext.Forms.IgnoreQueryFilters().FirstOrDefault(f => f.Id == 1).Sprint;

作为一则旁注,我想说明的是我在 StartUp.cs 中使用了懒加载代理。
services.AddDbContext<ApplicationDbContext>(options => 
    options.UseLazyLoadingProxies().UseSqlServer(connectionString));

我的模型比这里给出的示例更复杂,因此不使用'Include()'和'ThenInclude()'. 使用include会使代码变得更加复杂和难以维护。


1
你尝试过使用.IgnoreQueryFilters()吗? - Fabio
查看帖子的编辑版本。我尝试使用IgnoreQueryFilters,但它似乎无法在嵌套属性上工作。 - Ido
如果我已经使用了延迟加载代理,这还有必要吗? - Ido
你尝试过包含导航属性吗?只是好奇你需要延迟加载的用例是什么? - Fabio
我们的模型非常复杂,有超过20个属性,每个属性都有自己的嵌套属性。在startup.cs中使用“UseLazyLoadingProxies()”比使用“include()”和“ThenInclude()”使代码更易于维护。 - Ido
显示剩余2条评论
1个回答

7

试试这个

var data = DbContext.Set<Table>().IgnoreQueryFilters().ToList();

或者

var data = DbContext.TableName.IgnoreQueryFilters().ToList();

查看我发布的编辑版本。我尝试使用IgnoreQueryFilters,但它似乎无法在嵌套属性上工作。 - Ido
1
我已经这样做了。我面临的问题是当我想检索软删除的导航属性时。 - Ido
你所建议的方法可以解决问题。但是我的模型比我举例的更加复杂,因此使用'Include()'和'ThanInclude()'会变得更加复杂和难以维护。我的问题是,如果我在startup.cs中已经使用了'UseLazyLoadingProxies()',为什么还需要使用'include()'呢? - Ido
你在ConfigureServices方法中添加了services.AddEntityFrameworkProxies()吗? - Farhad Zamani
不,我没有这样做,但我尝试在注册applicationDbContext之后在ConfigureServices中添加它。但是它没有起作用。(这次,我没有使用Include()) - Ido
显示剩余2条评论

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接