6

我正在尝试创建一个通用类,用于为实体框架 (5) 编写查询。

我让它工作,唯一的问题是该值是作为查询的常量而不是作为参数注入的。这减少了 EF 缓存查询并在以后重用它的可能性。

这是我到目前为止得到的。

public class MinDateFilter<T> : IFilter<T> where T : class
{
    private readonly Expression<Func<T, bool>> _predicate;

    public MinDateCandidateFilter(Expression<Func<T, DateTime>> propertySelector, DateTime from)
    {
        from = from.Date.AddDays(-1);
        from = new DateTime(from.Year, from.Month, from.Day, 23, 59, 59, 999);

        Expression value = Expression.Constant(from, typeof(DateTime));
        //ParameterExpression variable = Expression.Variable(typeof(DateTime), "value");

        MemberExpression memberExpression = (MemberExpression)propertySelector.Body;
        ParameterExpression parameter = Expression.Parameter(typeof(T), "item");
        Expression exp = Expression.MakeMemberAccess(parameter, memberExpression.Member);

        Expression operation = Expression.GreaterThan(exp, value);
        //Expression operation = Expression.GreaterThan(exp, variable);
        _predicate = Expression.Lambda<Func<T, bool>>(operation, parameter);
    }

    public IQueryable<T> Filter(IQueryable<T> items)
    {
        return items.Where(_predicate);
    }
}

这个类可以通过两种方式使用:

通过对其进行子分类:

public class MinCreationDateCandidateFilter : MinDateFilter<Candidate>
{
    public MinCreationDateCandidateFilter(DateTime @from) : base(c => c.CreationDate, @from) {}
}

或者简单地通过实例化它:

var filter = new MinDateFilter<Entities.Transition>(t => t.Date, from.Value);

这是我迄今为止设法实现的目标:

SELECT 
[Extent1].[Id] AS [Id]
-- Other fields
FROM [dbo].[Candidates] AS [Extent1]
WHERE [Extent1].[CreationDate] > convert(datetime2, '1982-12-09 23:59:59.9990000', 121)

代替

SELECT 
[Extent1].[Id] AS [Id]
-- Other fields
FROM [dbo].[Candidates] AS [Extent1]
WHERE [Extent1].[CreationDate] > @p__linq__0

如果我取消注释两条注释行并注释上面的两条,我会收到一条错误消息,指出参数“值”未绑定。

我希望我提供了所有有用的细节:)

4

1 回答 1

13

当参数作为 a 传递时ConstantExpression,如下所示:

Expression.Constant(myString)

...它将在结果查询中生成一个固定的常量符号:

SELECT 
[Extent1].[Id] AS [Id], 
[Extent1].[Bar] AS [Bar], 
FROM [dbo].[Foo] AS [Extent1]
WHERE [Extent1].[Bar] = "Some text"

(f => f.Bar == myString))如果您像我使用 Expression Tree Visualizer 那样使用某种工具分析表达式,您会看到参数实际上是一个MemberExpression. 因此,如果您想要在结果查询中添加一个参数,则必须传递对象的属性之类的东西,或者更方便的匿名类型:

Expression.Property(
    Expression.Constant(new { Value = myString }),
    "Value"
)

这样,您将传递刚刚创建的对象的属性,并且您的表达式树得到 a MemberExpression,结果如下CommandText

SELECT 
[Extent1].[Id] AS [Id], 
[Extent1].[Bar] AS [Bar], 
FROM [dbo].[Foo] AS [Extent1]
WHERE [Extent1].[Bar] = @p__linq__0
于 2014-02-07T19:52:50.493 回答