我有一个具有以下架构的表:
create table test
(
foo1 nvarchar(4),
foo2 nvarchar(30)
)
create unique index test_foo1 on test (foo1);
当使用 Entity 使用 EF 创建实体时,它生成了一个类:
public class Test
{
public string foo1 {get; set;}
public string foo2 {get; set;}
}
因此,在编辑这条记录时,我正在构建如下所示的动态表达式树,以查找是否存在可供实际编辑的数据库记录:
Expression combinedExpression = null;
foreach (string propertyName in keyColumnNames)
{
var propertyInfo = typeof(Entity).GetProperty(propertyName);
var value = propertyInfo.GetValue(entityWithKeyFieldsPopulated);
var type = propertyInfo.PropertyType;
Expression e1 = Expression.Property(pe, propertyName);
Expression e2 = Expression.Constant(value, type);
Expression e3 = Expression.Equal(e1, e2);
if (combinedExpression == null)
{
combinedExpression = e3;
}
else
{
combinedExpression = Expression.AndAlso(combinedExpression, e3);
}
}
return combinedExpression;
每当我编辑实体“Test”并向属性 foo1 提供“null”时,它就会将数据库查询为“select * from test where foo1 == null”。我如何构建表达式来实际创建一个 where 子句作为“select *from test where foo1 is null”?
最佳答案
可能只是查询处理器没有生成 foo1 is null
表达式,因为 foo1
在唯一索引中。它不会为空,因此不会生成该表达式。
我有一些表,其中的列声明为不可为空,where x.column == null
在其位置生成 where 0 = 1
。它知道这永远不会是真的。也许这里也发生了同样的事情?
关于c# - 通过动态创建 linq 查询在 c# 中为 Sql 等效项 "column is null"创建 Linq 表达式,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53015353/