【发布时间】:2019-03-31 14:31:48
【问题描述】:
我有一个具有以下架构的表:
create table test
(
foo1 nvarchar(4),
foo2 nvarchar(30)
)
create unique index test_foo1 on test (foo1);
当使用 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”并将“null”提供给属性 foo1 时执行此操作,它会将数据库查询为“select * from test where foo1 == null”。如何构建实际创建 where 子句作为“select *from test where foo1 is null”的表达式?
【问题讨论】:
-
你看的是EF生成的实际SQL查询,还是只看表达式的ToString()?
-
@DaveM 我运行 SQL Profiler 来查看它正在生成什么查询。它生成 foo1 == null not foo1 is null
-
什么 SQL 提供程序?当我使用 MS SQL Server 进行测试时,
Expression.Equal生成column IS NULL。如果进行 lambda 测试,会生成什么 SQL(例如db.Where(r => r.foo1 == null))? -
@NetMage ,MS SQL OLE DB。当我进行 lambda 测试时,它生成 db.Where(r => r.foo1 == null) 并在 sql profiler 中生成为“from test where foo1 = null”
-
MS SQL OLE DB 对我来说没有意义。 LINQ to SQL 有一个 MS SQL 提供程序,但 OLEDB 与它有什么关系?或者您正在使用 LINQ to Datasets?
标签: c# sql linq linq-expressions