简体   繁体   English

Linq .FirstOrDefault不起作用

[英]Linq .FirstOrDefault not working

I have a database where if the selected dvd's is not taken back (so the date of the arrival is empty) it should write to the linklabel that that the dvd is still rented: 我有一个数据库,如果未收回所选的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";
}

If I use First() it says that it is empty, but if I use FirstOrDefault() it shows null to all movies even if they have taken back date in the database. 如果我使用First()则说它是空的,但是如果我使用FirstOrDefault()则它对所有电影都显示null ,即使它们已经在数据库中取回了日期。

When the documentation talk about empty, they talk about the source, the list of elements. 当文档谈论空时,他们谈论的是源,元素列表。 So if FirstOrDefault and First get a source that has no elements, the default value will be returned or an exception is thrown. 因此,如果FirstOrDefaultFirst获得没有元素的源,则将返回默认值或引发异常。

'Empty' does not refer to 'empty' values, like a null-value. “空”不引用“空”值,例如空值。

To get what you want, try this: 要获得所需的内容,请尝试以下操作:

// 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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM