[英]Create Linq Expression for Sql Equivalent “column is null” in c# by creating linq query dynamically
I have a table with following schema: 我有一个包含以下架构的表:
create table test
(
foo1 nvarchar(4),
foo2 nvarchar(30)
)
create unique index test_foo1 on test (foo1);
When created entity using Entity using EF, it generated a class like: 当使用EF使用Entity创建实体时,它生成了一个类,如:
public class Test
{
public string foo1 {get; set;}
public string foo2 {get; set;}
}
So when editing this record, I am building dynamic expression tree like below to find if there is a database record for actually editing: 因此,在编辑此记录时,我正在构建如下所示的动态表达式树,以查找是否存在实际编辑的数据库记录:
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;
By doing this whenever I am editing entity "Test" and supplying "null" to property foo1 it is querying database as "select * from test where foo1 == null". 通过这样做,每当我编辑实体“Test”并向属性foo1提供“null”时,它将查询数据库为“select * from test where foo1 == null”。 How can I build expression that actually creates a where clause as "select *from test where foo1 is null" ?
我如何构建实际创建where子句的表达式为“select * from test where foo1为null”?
It might just be that the query processor is not generating an foo1 is null
expression because foo1
is in a unique index. 可能只是查询处理器没有生成
foo1 is null
表达式,因为foo1
在唯一索引中。 It won't be null so it won't generate that expression. 它不会为null,因此不会生成该表达式。
I have some tables with columns declared not nullable and where x.column == null
generates where 0 = 1
in its place. 我有一些表声明不可为空的表,
where x.column == null
生成的where 0 = 1
。 It knows it will never be true. 它知道它永远不会是真的。 Perhaps the same is happening here?
也许这里也发生了同样的事情?
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.