vam*_*nam 5 c# sql linq linq-expressions
我有一个具有以下架构的表:
create table test
(
foo1 nvarchar(4),
foo2 nvarchar(30)
)
create unique index test_foo1 on test (foo1);
Run Code Online (Sandbox Code Playgroud)
当使用EF使用Entity创建实体时,它会生成类似以下的类:
public class Test
{
public string foo1 {get; set;}
public string foo2 {get; set;}
}
Run Code Online (Sandbox Code Playgroud)
因此,在编辑此记录时,我将像下面那样构建动态表达式树,以查找是否存在用于实际编辑的数据库记录:
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;
Run Code Online (Sandbox Code Playgroud)
每当我编辑实体“ Test”并向属性foo1提供“ null”时,通过执行此操作,就将数据库查询为“ select * from test where foo1 == null”。如何构建实际上创建where子句的表达式,例如“从test * foo1为null的地方选择”?
Jef*_*ado -1
可能只是查询处理器没有生成表达式,foo1 is null因为foo1它位于唯一索引中。它不会为空,因此不会生成该表达式。
我有一些表,其中的列声明为不可为空并在其位置where x.column == null生成。where 0 = 1它知道这永远不会是真的。也许同样的事情也发生在这里?
| 归档时间: |
|
| 查看次数: |
134 次 |
| 最近记录: |