[英]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.