簡體   English   中英

如何在EF中的包含實體中添加where子句?

[英]How can I add a where clause to an in included entity in EF?

我有三張桌子

  • 人員表(通用人員表)
  • 客戶表(每個客戶都是一個人)
  • 地址表(每個客戶都有一個地址)

我需要從實體框架查詢數據庫,以查找人名和城市,州的匹配情況。 這是我所擁有的,但除非我從where子句中刪除州和城市,否則它不起作用

var customer = db.tbl_Person
    .Include(t => t.tbl_Customer.tbl_Address)
    .Where(t => t.VendorID == person.VendorID &&
                t.FirstName == person.FirstName &&
                t.LastName == person.LastName &&
                t.tbl_Customer.tbl_Address.State == address.State &&
                t.tbl_Customer.tbl_Address.City == address.City).ToList();

任何幫助都會很感激 - 我仍然是EF的新手。 正如我在下面的評論中所述,我得到的錯誤是

附加信息:無法將類型為“System.Linq.Expressions.FieldExpression”的對象強制轉換為“System.Linq.Expressions.ParameterExpression”。

var customer = db.tbl_Person
    .Include(t => t.tbl_Customer.tbl_Address)
    .Where(t => t.VendorID == person.VendorID &&
                t.FirstName == person.FirstName &&
                t.LastName == person.LastName)
    .ToList()
    .Where(t => t.tbl_Customer?.tbl_Address != null &&
                t.tbl_Customer.tbl_Address.State == address.State &&
                t.tbl_Customer.tbl_Address.City == address.City).ToList();

分解where應該確保調用查詢的次要部分。 此外,您需要確保兩個介入記錄不為空。

編輯:在wheres之間添加了ToList()。 為什么? 因為注釋中的錯誤反映出Linq正在嘗試使用非參數化字段作為參數化字段來動態構建查詢。 通過在其間放置.ToList(),它會強制查詢在第一個子集上運行,然后過濾State和City設置的查詢。

我認為包含相關屬性的方式在EF 7上有所改變。試試這個:

var customer = db.tbl_Person
    .Include(t => t.tbl_Customer).ThenInclude(c=>c.tbl_Address)
    .Where(...).ToList();

您需要使用ThenInclude方法來包含您的第二級。 檢查此參考

更新

我猜您正在檢查tbl_Customer是否為null因為您在PersonCustomer之間存在條件關系。 檢查您是否與Customer相關的另一種方法是使用FK屬性。 例如,如果CustomerId的類型為intCustomer始終與Address (必需關系)相關,則可以執行以下操作:

var customer = db.tbl_Person
    .Include(t => t.tbl_Customer.tbl_Address)
    .Where(t => t.VendorID == person.VendorID &&
                t.FirstName == person.FirstName &&
                t.LastName == person.LastName &&
                t.tbl_CustomerId != 0 && // compare with default value of your FK property
                t.tbl_Customer.tbl_Address.State == address.State &&
                t.tbl_Customer.tbl_Address.City == address.City).ToList();

暫無
暫無

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

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