簡體   English   中英

EF Core 6 - 如何讓多個 DbSets 預過濾同一個表

[英]EF Core 6 - How to have multiple DbSets to prefilter same table

我正在嘗試找到解決此問題的最佳方法。 我有一個名為Customer的數據庫表。 此表有一個名為Status的 boolean 列,它告訴我此客戶是否處於活動狀態。 我想創建一種“全局查詢過濾器”以僅提取活躍客戶列表,但我知道如果我在當前擁有的唯一 DbSet 上配置查詢過濾器,我將始終只過濾活躍客戶,這對我不利,因為有時我還需要不活動的(例如在管理頁面中)。

我的想法是創建這樣的東西,但我不知道如何配置它:

public class Customer {
   //…properties

   public bool Status {get; set;}
}

public DbSet<Customer> Customers {get; set;}
public DbSet<Customer> CustomersActive {get; set;}

這可能嗎?

改為公開IQueryable<Customer>屬性:

public DbSet<Customer> Customers {get; set;}
public IQueryable<Customer> CustomersActive => Customers.Where(c => c.Status);
public IQueryable<Customer> CustomersInactive => Customers.Where(c => !c.Status);

順便說一句, bool Status的更好名稱是ActiveIsActive

請注意,您可以鏈接Where調用。 這相當於將條件與&&結合起來。

var result = Customers
    .Where(c => c.Status)
    .Where(c => c.Name.StartsWith("A"));

相當於

var result = Customers
    .Where(c => c.Status && c.Name.StartsWith("A"));

因此,這種方法不會限制您查詢的可能性。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM