【发布时间】:2020-08-08 20:29:23
【问题描述】:
我很难尝试使用 linq 实现 nullcheck (isNull, isNotNull) 表达式。 这是我的代码的一部分:
//create a blog collection
var blogsCollection = new List<Blog>();
for (var i = 1; i <= 15; i++)
{
var b = new Blog()
{
BlogId = i,
Url = $"http://{i}.blog.com",
CreatedAt = DateTime.UtcNow.AddDays(-i),
};
blogsCollection.Add(b);
}
ParameterExpression parameterExpression = Expression.Parameter(typeof(Blog), "item");
Expression propertyExpression = Expression.Property(parameterExpression, "BlogId");
Expression targetExpression = Expression.Constant(null, propertyExpression.Type);
Expression exp = Expression.Equal(propertyExpression, targetExpression);
var filter=Expression.Lambda<Func<Blog, bool>>(exp, parameterExpression).Compile();
var blogs = (List<Blog>)blogsCollection.Where(filter);
此代码引发异常: 参数类型不匹配
如果我将 targetExpression 更改为(没有类型转换): 表达式 targetExpression = Expression.Constant(null);
然后它抛出一个不同的异常: System.InvalidOperationException : 二元运算符 Equal 没有为类型 'System.Int32' 和 'System.Object' 定义
关于如何在 Linq 中进行空检查的任何想法?我已经在这里检查过 SO,但它们似乎都不起作用。
【问题讨论】:
-
看起来
BlogId是int?你为什么要测试它是否为空?整数不能为空。尝试创建int类型的常量null当然会失败。如果把"BlogId"改成"Url",everything is fine(在添加必要的.ToList()之后) -
还有
blogsCollection.Where(filter).ToList()不是(List<Blog>)blogsCollection.Where(filter) -
这个想法是将其转换为 EF 数据库查询。这就是为什么需要 nullcheck 的原因。代码来自我的测试方法,但是在ef版本中,错误是一样的
-
错误来自
Expression.Contant(null, typeof(int))- 这只是一个无意义的要求。如果数据库列可能为空,那么模型中的BlogId可能是int?,而不是int。如果是这种情况,everything is fine -
你是对的!我需要睡觉...谢谢
标签: c# linq expression