[英]Linq .FirstOrDefault not working
我有一個數據庫,如果未收回所選的dvd(因此到達日期為空),則應向linklabel寫入該dvd仍在出租的信息:
var j = (from s in db.Rentals where s.MovieTitle == tb_movietitle.Text
select s.takenbackdate).FirstOrDefault();
if (j == null)
{
linkLabel1.Text = "The dvd is still rented";
}
else
{
linkLabel1.Text = "Rentable";
}
如果我使用First()
則說它是空的,但是如果我使用FirstOrDefault()
則它對所有電影都顯示null
,即使它們已經在數據庫中取回了日期。
當文檔談論空時,他們談論的是源,元素列表。 因此,如果FirstOrDefault
和First
獲得沒有元素的源,則將返回默認值或引發異常。
“空”不引用“空”值,例如空值。
要獲得所需的內容,請嘗試以下操作:
// Find the first DVD with the given title. If not found, an exception is thrown.
var j = (from s in db.Rentals where s.MovieTitle == tb_movietitle.Text).First();
// If the taken back date is null, it is still rented.
if (j.takenbackdate == null)
{
linkLabel1.Text = "The dvd is still rented";
}
else
{
linkLabel1.Text = "Rentable";
}
您可以這樣嘗試:
var j = db.Rentals.Where(s=>s.MovieTitle.Contains(tb_movietitle.Text).Select(s=>s.takenbacktime ).FirstOrDefault();
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.