我想为IQueryable创建自定义表达式。示例扩展方法:
public static IQueryable<T> GetByIntTest<T>(this IQueryable<T> qSource, Expression<Func<T, int?>> field, int? value)
{
if (value == null)
return qSource;
ConstantExpression constantExpression = Expression.Constant(value, typeof(int?));
BinaryExpression binaryExpression = Expression.Equal(field.Body, constantExpression);
var predicate = Expression.Lambda<Func<T, bool>>(binaryExpression, field.Parameters);
return qSource.Where(predicate);
}
它有效,但问题是它转换为非参数化的sql。
例如没有扩展名的代码
int userId = 3;
var testUsual = Context.Set<User>().Where(u => u.Id == userId);
转换为下一个sql
SELECT [Extent1].[Id] AS [Id],
[Extent1].[FirstName] AS [FirstName],
[Extent1].[LastName] AS [LastName],
FROM [dbo].[User] AS [Extent1]
WHERE [Extent1].[Id] = @p__linq__0
和扩展方法
int userId = 3;
var testExtension = Context.Set<User>().GetByIntTest(u => u.Id, userId);
翻译成
SELECT [Extent1].[Id] AS [Id],
[Extent1].[FirstName] AS [FirstName],
[Extent1].[LastName] AS [LastName],
FROM [dbo].[User] AS [Extent1]
WHERE 3 = [Extent1].[Id]
那么如何在sql中编写用于生成 @p_ linq _0 之类的表达式?
更新
感谢 usr 回答,我重写了我的扩展方法,现在它根据需要生成 @p_ linq _0 。
public static IQueryable<T> GetByIntTest<T>(this IQueryable<T> qSource, Expression<Func<T, int?>> field, int? value)
{
if (value == null)
return qSource;
var binaryExpression = Expression.Equal(field.Body, ExpressionClosureFactory.GetField(value));
var predicate = Expression.Lambda<Func<T, bool>>(binaryExpression, field.Parameters);
return qSource.Where(predicate);
}
public class ExpressionClosureFactory
{
public static MemberExpression GetField<TValue>(TValue value)
{
var closure = new ExpressionClosureField<TValue>
{
ValueProperty = value
};
return Expression.Field(Expression.Constant(closure), "ValueProperty");
}
class ExpressionClosureField<T>
{
public T ValueProperty;
}
}
答案 0 :(得分:3)
我遇到了这个问题。您正在生成u => u.Id == 3
作为表达式,而C#编译器将生成:
class CompilerGeneratedClosure { public int UserId; }
var closure = new CompilerGeneratedClosure() { UserId = 3 };
u => u.Id == closure.UserId
就像C#编译器一样。创建一个类来保存ID或使用元组。将closure
作为常量表达式注入。