![](/img/trans.png)
[英]What is the equivalent code of SQL query in C# with linq to datatable?
[英]Create Linq Expression for Sql Equivalent “column is null” in c# by creating linq query dynamically
我有一个包含以下架构的表:
create table test
(
foo1 nvarchar(4),
foo2 nvarchar(30)
)
create unique index test_foo1 on test (foo1);
当使用EF使用Entity创建实体时,它生成了一个类,如:
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为null”?
可能只是查询处理器没有生成foo1 is null
表达式,因为foo1
在唯一索引中。 它不会为null,因此不会生成该表达式。
我有一些表声明不可为空的表, where x.column == null
生成的where 0 = 1
。 它知道它永远不会是真的。 也许这里也发生了同样的事情?
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.