簡體   English   中英

如何在實體框架中使用where子句?

[英]How to use the where clause in entity framework?

我正在嘗試查詢我的EF Code First數據庫,因此它將返回當前登錄用戶進行的所有預訂。 我不太了解語法的正確性,希望有人可以指出正確的方向。

我嘗試實現此目標的兩種不同方式:

List<Booking> bookings = new List<Booking>();
string userid = User.Identity.GetUserId();
foreach(var b in db.Bookings.Where(b => b.Customer.Id == userid))
{
    bookings.Add(b);
}
string userid = User.Identity.GetUserId();
var bookings = db.Bookings.Include(b => b.Customer).Include(b => b.Invoice).Include(b => b.Payment).Include(b => b.Vehicle).Where(b => b.Customer.Id == userid);
return View(bookings.ToList());

這些方式均未返回數據庫中的任何預訂,因此我確定我的邏輯在此處錯誤。 任何幫助,將不勝感激。

在第一個查詢中,您忘了包括“客戶”導航屬性,因此客戶總是失敗,並且不會返回任何預訂。

盡管在第二個查詢中,您已包括客戶,發票等! 在這種情況下,僅在客戶預訂了發票,付款等之后才返回客戶。

此查詢應與您一起使用:

string userid = User.Identity.GetUserId();
var bookings = db.Bookings
                 .Include(b => b.Customer)
                 .Where(b => b.Customer.Id == userid)
                 .ToList();

return View(bookings);

看來您使用的是啟用了EagerMode的EF,因此您需要在where條件中Include客戶或任何相關字段。

我的題外話推薦:

請不要返回直接從ORM獲取的實體。 首先,將它們轉換為DTO(使用AutoMapper或任何其他對象映射器)

暫無
暫無

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

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