将参数传递给linq谓词 [英] Passing a parameter to a linq predicate

查看:56
本文介绍了将参数传递给linq谓词的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想编写如下代码-

    public IQueryable<Invoice> InvoiceFilterForMonthAndYear(DateTime? monthAndYear = null)
    {
        var invoices = _invoices.Where(MonthAndYearPredicate(monthAndYear);
        return invoices;
    }

    private bool MonthAndYearPredicate(Invoice invoice, DateTime? monthAndYear)
    {
        //code to check if the invoice start or end dates is from the falls in the month I am checking for
    }

但是我不能使用这样的谓词,因为该谓词只需要一个参数.

But I can't use a predicate like that because the predicate expects just one parameter.

我知道我可以在InvoiceFilterForMonthAndYear中编写Where子句来完成工作,但是 我想将比较逻辑放入自己的方法中.

I know I could write a Where clause in InvoiceFilterForMonthAndYear to do the work, but I want to put the logic for the comparison into its own method.

推荐答案

如果您的比较方法返回一个表达式,它将起作用:

It works if your method for comparison returns an expression:

private Expression<Func<Invoice,bool>> MonthAndYearPredicate(
    DateTime? monthAndYear)
{
    return i => i.StartDate >= monthAndYear; // or whatever
}

要像您的示例中那样被调用:

To be called like in your example:

var invoices = _invoices.Where(MonthAndYearPredicate(monthAndYear));

或者您可以将逻辑提取到IQueryable<Invoice>的扩展方法中:

Or you could extract the logic into an extension method of IQueryable<Invoice>:

public static class QueryExtensions
{
    public static IQueryable<Invoice> WhereMonthAndYear(
        this IQueryable<Invoice> query, DateTime? monthAndYear)
    {
        return query.Where(i => i.StartDate >= monthAndYear); // or whatever
    }
}

要这样称呼:

var invoices = _invoices.WhereMonthAndYear(monthAndYear);

请记住,在两种情况下,您都必须使用EF可以转换为SQL的有效LINQ-to-Entities表达式.它只会使表达式可重复用于不同的查询,而不会扩展其功能.

Keep in mind that in both cases you have to use valid LINQ-to-Entities expressions that EF can translate into SQL. It only makes the expressions reusable for different queries but does not extend its capabilities.

这篇关于将参数传递给linq谓词的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆