C#Linq检查数据库中是否存在内容

时间:2014-04-20 13:08:59

标签: c# linq null

我有一个电影数据库,表格上的列表框显示标题。如果用户选择要租借它的DVD,应用程序必须检查该电影标题(外键)是否已经在租赁表中。如果是,则将其写入数据库中,如果不是写入:不在数据库中。如果我使用下面的代码,当电影标题不在租赁表中时,我会收到错误,因此该NULL存在一些问题。我该如何解决这个问题?

private void bt_Letsrent_Click(object sender, EventArgs e)
        {
            var c1 = (from s in db.Rent where s.Movietitle == (string)listbox1.SelectedValue select s).FirstOrDefault();

            if (c1.Movietitle==null)
            {
                MessageBox.Show("Not in the database");
            }
            else
            {
                MessageBox.Show("In the database");
            }
}

1 个答案:

答案 0 :(得分:0)

您可以获得满足以下条件的物品数量:

int count= db.Rent.Count(s => s.Movietitle == (string)listbox1.SelectedValue);

if (count>0)
{
    MessageBox.Show("In the database");
}
else
{
    MessageBox.Show("Not in the database");
}
相关问题