[英]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
的更好名稱是Active
或IsActive
。
請注意,您可以鏈接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.