c# - 短路 linq 查询抛出 null 错误

标签 c# linq entity-framework-6

我在尝试让这个 linq 语句工作时遇到了一些麻烦。我正在使用 linq 查询设置搜索。我想做的是,如果搜索为空或为空,则让它忽略过滤的该部分。所以我设置了许多 where 子句来短路 where 子句,如下所示:

tvContent.LoadContent(
    Live.Ringtones
        .Where(x => cbSeller.SelectedValue== null || 
               x.Property.SellerID == (int)cbSeller.SelectedValue)
        .Where(x => cbProperty.SelectedValue==null || 
               x.PropertyID == (int)cbProperty.SelectedValue)
        .Where(x => string.IsNullOrEmpty(tbContentID.Text) || 
               x.RingtoneID == ContentID)
        .Where(x => string.IsNullOrEmpty(tbContentName.Text) || 
               x.RingtoneName == tbContentName.Text).ToList());

但是当我这样做时,我不断遇到空引用问题。 cbProperty 为空,并且 selectedValue 在我调试时确实显示为 null,但它仍然表示存在空引用问题。我做错了什么?

最佳答案

为什么要将不变量放入 where 子句中?

var ringtones = Live.Ringtones;

if (cbSeller.SelectedValue!= null)
    ringtones = ringtones.Where(x=> x.Property.SellerID 
                                     == (int)cbSeller.SelectedValue);

if (cbProperty.SelectedValue!= null)
    ringtones = ringtones.Where(x=> x.PropertyID 
                                     == (int)cbProperty.SelectedValue);

if(!string.IsNullOrEmpty(tbContentID.Text))
    ringtones.Where(x=> x.RingtoneID == ContentID)

if(!string.IsNullOrEmpty(tbContentName.Text) )
    ringtones.Where(x => x.RingtoneName == tbContentName.Text)

tvContent.LoadContent(ringtones.ToList());

关于c# - 短路 linq 查询抛出 null 错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26981169/

相关文章:

c# - 使用 lambda 表达式的测试方法的静态分析 CA1811 错误

c# - 获取更改 FileInfo.lastAccessTime 或 FileInfo.lastWriteTime 的进程

c# - 将 Attach 与 Linq To Sql 和存储过程结合使用

c# - LINQ 多连接挂起

c# - 在 Entity Framework 6 中使用 Effort 的正确方法是什么?

c# - 使用具有自己的事务范围的多个 DbContext

java - 多线程套接字服务器 - 客户端相互通信

c# - 如何在 EF6 Code First 中将泛型类型与数据库上下文一起使用

c# - 编译器错误 : An expression tree may not contain a dynamic operation

c# - 如何在 Entity Framework 6 中以编程方式为 MS SQL 创建连接字符串?