2

我有一个实体类

public class BookPage {
    public int PageIndex { get; set; }
}

然后我有一个表达:

Expression<Func<int, bool>> pageIndexCondition = idx => idx == 1;

和我想要的表达:

Expression<Func<BookPage, bool>> pageCondition = bookPage => bookPage.PageIndex == 1;

问题:如何使用pageIndexConditionLINQ-to-SQL 查询,或者如何转换pageIndexConditionpageCondition

编辑:另一个不太优雅但仍符合我要求的解决方案是:

Expression<Func<T, bool>> GetPageIndexCondition(Expression<Func<T, int>> selector) {
     return (T item) => selector(item) < 10; // This won't work because selector is Expression, so how to implement this correctly?
}

...

var pageCondition = GetPageIndexCondition(page => page.PageIndex);
4

2 回答 2

1

我喜欢做这些事情,尽管正如其他人所说,可能有更有效和更好的方法来做到这一点:

void Main()
{
    Expression<Func<int, bool>> pageIndexCondition = idx => idx == 1;
    Expression<Func<BookPage, bool>> converted = ExpressionConverter.Convert(pageIndexCondition);
}

public class ExpressionConverter : ExpressionVisitor
{
    public static Expression<Func<BookPage, bool>> Convert(Expression<Func<int, bool>> e)
    {
        var oldParameter = e.Parameters.First();
        var newParameter = Expression.Parameter(typeof(BookPage), "bp");
        Expression<Func<BookPage, int>> x = (BookPage bp) => bp.PageIndex;
        var property = ((x.Body as MemberExpression).Member as PropertyInfo);
        var memberAccess = Expression.Property(newParameter, property);

        var converter = new ExpressionConverter(oldParameter, memberAccess);
        return (Expression<Func<BookPage, bool>>)Expression.Lambda(converter.Visit(e.Body), newParameter);
    }

    private ParameterExpression pe;
    private Expression replacement;

    public ExpressionConverter(ParameterExpression pe, Expression replacement)
    {
        this.pe = pe;
        this.replacement = replacement;
    }

    protected override Expression VisitParameter(ParameterExpression node)
    {
        if(node == pe)
            return replacement;

        return base.VisitParameter(node);
    }

}
于 2013-05-13T23:31:21.673 回答
0
var pages = new List<BookPage>
                {
                    new BookPage { PageIndex = 1 }, 
                    new BookPage { PageIndex = 2 }
                };

Expression<Func<BookPage, bool>> pageCondition = bookPage => bookPage.PageIndex == 1;

BookPage result = pages.AsQueryable().Single(pageCondition);

如果您想要通过 id 进行通用选择,则必须执行以下操作;

public virtual IEnumerable<TEntity> Get(Expression<Func<TEntity, bool>> filter = null)
{
    if (filter != null)
    {
        query = query.Where(filter);
    }
}

这在您的通用存储库中。

于 2013-05-10T14:19:19.717 回答