【问题标题】:Disable softDelete Query filters for navigation properties禁用导航属性的 softDelete 查询过滤器
【发布时间】:2019-07-08 06:43:54
【问题描述】:

我使用 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 会使代码更加复杂和不可维护。

【问题讨论】:

  • 你试过.IgnoreQueryFilters()吗?
  • 查看帖子的编辑版本。我曾尝试使用 IgnoreQueryFilters,但它似乎确实适用于嵌套属性。
  • 您需要包含导航属性。 dbContext.Forms.Include(f =&gt; f.Sprint).IgnoreQueryFilters().FirstOrDefault(f =&gt; f.Id == 1).Sprint
  • 如果我已经使用了延迟加载代理,这有必要吗?
  • 您是否尝试包含导航属性?只是好奇需要延迟加载的用例是什么?

标签: c# .net-core entity-framework-core soft-delete


【解决方案1】:

试试这个

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

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

【讨论】:

  • 查看我帖子的编辑版本。我曾尝试使用 IgnoreQueryFilters,但它似乎确实适用于嵌套属性。
  • 您必须声明一个属性,例如 IsDelete 为 bool,当记录是软删除时,将 IsDelete 属性更改为 True 并设置查询过滤器。例如:modelBuilder.Entity().HasQueryFilter(a => !a.IsDelete);
  • 我已经这样做了。我面临的问题是当我想检索软删除的导航属性时。
  • applicationDbContext.Forms.IgnoreQueryFilters().Include(a=>a.Sprint ).FirstOrDefault(f => f.Id == 1).Sprint;
  • 你建议的作品。但是我的模型比我给出的例子更复杂。所以使用 'Include()' 和 'ThanInclude()' 会更加复杂和不可维护。我的问题是为什么必须使用 'include()' ,如果我已经在 startup.cs 中使用了 'UseLazyLoadingProxies()'
猜你喜欢
  • 2013-01-14
  • 1970-01-01
  • 2014-04-18
  • 1970-01-01
  • 2017-03-24
  • 2021-06-20
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多