繁体   English   中英

Linq .FirstOrDefault不起作用

[英]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 ,即使它们已经在数据库中取回了日期。

当文档谈论空时,他们谈论的是源,元素列表。 因此,如果FirstOrDefaultFirst获得没有元素的源,则将返回默认值或引发异常。

“空”不引用“空”值,例如空值。

要获得所需的内容,请尝试以下操作:

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