【问题标题】:Pass LINQ expression to another QueryProvider将 LINQ 表达式传递给另一个 QueryProvider
【发布时间】:2012-05-22 14:23:45
【问题描述】:

我有一个简单的自定义 QueryProvider,它接受一个表达式,将其转换为 SQL 并查询一个 sql 数据库。

我想在 QueryProvider 中创建一个小型缓存,用于存储经常访问的对象,以便在不命中数据库的情况下进行检索。

QueryProvider 有方法

public object Execute(System.Linq.Expressions.Expression expression)
{
    /// Builds an SQL statement from the expression, 
    /// executes it and returns matching objects
}

缓存作为这个 QueryProvider 类中的一个字段,是一个简单的通用列表。

如果我使用 List.AsQueryable 方法并将上面的表达式传递给 List.AsQueryable 的 Provider 的 Execute 方法,它不会按预期工作。看起来当一个表达式被编译时,初始的 QueryProvider 成为了一个不可或缺的部分。

是否可以将表达式传递给后续的 QueryProvider 并根据需要执行该表达式?

调用代码大致如下:

public class QueryProvider<Entity>()
{
    private List<TEntity> cache = new List<Entity>();

    public object Execute(System.Linq.Expressions.Expression expression)
    {
        /// check whether expression expects single or multiple result
        bool isSingle = true;

        if (isSingle)
        {
            var result = this.cache.AsQueryable<Entity>().Provider.Execute(expression);
            if (result != null) 
                return result;
        }

        /// cache failed, hit database
        var qt = new QueryTranslator();
        string sql = qt.Translate(expression);
        /// .... hit database
    }
} 

它不会返回错误,而是卡在循环中,反复调用同一个提供程序。

这里有更多代码显示我正在尝试做的事情:

收藏:

class Collection<Entity>
{

    internal List<Entity> cacheOne { get; private set; }
    internal Dictionary<Guid, Entity> cacheTwo { get; private set; }

    internal Collection()
    {
        this.cacheOne = new List<Entity>();
        this.cacheTwo = new Dictionary<Guid, Entity>();
    }

    public IQueryable<Entity> Query()
    {
        return new Query<Entity>(this.cacheOne, this.cacheTwo);
    }

}

查询:

class Query<Entity> : IQueryable<Entity>
{
    internal Query(List<Entity> cacheOne, Dictionary<Guid, Entity> cacheTwo)
    {
        this.Provider = new QueryProvider<Entity>(cacheOne, cacheTwo);
        this.Expression = Expression.Constant(this);
    }

    internal Query(IQueryProvider provider, Expression expression)
    {
        this.Provider = provider;
        if (expression != null)
            this.Expression = expression;
    }

    public IEnumerator<Entity> GetEnumerator()
    {
        return this.Provider.Execute<IEnumerator<Entity>>(this.Expression);
    }

    System.Collections.IEnumerator System.Collections.IEnumerable.GetEnumerator()
    {
        return this.GetEnumerator();
    }

    public Type ElementType
    {
        get { return typeof(Entity); }
    }

    public System.Linq.Expressions.Expression Expression { get; private set; }

    public IQueryProvider Provider { get; private set; }
}

查询提供者:

class QueryProvider<Entity> : IQueryProvider
{

    private List<Entity> cacheOne;
    private Dictionary<Guid, Entity> cacheTwo;

    internal QueryProvider(List<Entity> cacheOne, Dictionary<Guid, Entity> cacheTwo)
    {
        this.cacheOne = cacheOne;
        this.cacheTwo = cacheTwo;   
    }

    public IQueryable<TElement> CreateQuery<TElement>(System.Linq.Expressions.Expression expression)
    {
        return new Query<TElement>(this, expression);
    }

    public IQueryable CreateQuery(System.Linq.Expressions.Expression expression)
    {
        throw new NotImplementedException();
    }

    public TResult Execute<TResult>(System.Linq.Expressions.Expression expression)
    {
        return (TResult)this.Execute(expression);
    }

    public object Execute(System.Linq.Expressions.Expression expression)
    {
        Iterator<Entity> iterator = new Iterator<Entity>(expression, cacheOne, cacheTwo);
        return (iterator as IEnumerable<Entity>).GetEnumerator();
    }
}

迭代器:

class Iterator<Entity> : IEnumerable<Entity>
{
    private Expression expression;
    private List<Entity> cacheOne;
    private Dictionary<Guid, Entity> cacheTwo;

    internal Iterator(Expression expression, List<Entity> cacheOne, Dictionary<Guid, Entity> cacheTwo)
    {
        this.expression = expression;
        this.cacheOne = cacheOne;
        this.cacheTwo = cacheTwo;
    }

    public IEnumerator<Entity> GetEnumerator()
    {
        foreach (var result in (IEnumerable<Entity>)this.cacheOne.AsQueryable<Entity>().Provider.Execute(expression))
        {
            yield return result;
        }

        foreach (var more in (IEnumerable<Entity>)this.cacheTwo.Values.AsQueryable<Entity>().Provider.Execute(expression))
        {
            yield return more;
        }
    }

    System.Collections.IEnumerator System.Collections.IEnumerable.GetEnumerator()
    {
        return this.GetEnumerator();
    }
}

程序:

class Program
{
    static void Main(string[] args)
    {
        /// Create collection + caches
        var collection = new Collection<Giraffe>();
        collection.cacheOne.AddRange(new Giraffe[] {
            new Giraffe() { Id = Guid.NewGuid(), DateOfBirth = new DateTime(2011, 03, 21), Height = 192, Name = "Percy" },
            new Giraffe() { Id = Guid.NewGuid(), DateOfBirth = new DateTime(2005, 12, 25), Height = 188, Name = "Santa" },
            new Giraffe() { Id = Guid.NewGuid(), DateOfBirth = new DateTime(1999, 04, 01), Height=144, Name="Clown" }
        });
        var cachetwo = new List<Giraffe>(new Giraffe[] {
            new Giraffe() { Id = Guid.NewGuid(), DateOfBirth = new DateTime(1980, 03,03), Height = 599, Name="Big Ears" },
            new Giraffe() { Id = Guid.NewGuid(), DateOfBirth = new DateTime(1985, 04, 02), Height= 209, Name="Pug" }
        });
        foreach (var giraffe in cachetwo)
            collection.cacheTwo.Add(giraffe.Id, giraffe);

        /// Iterate through giraffes born before a certain date
        foreach (var result in collection.Query().Where(T => T.DateOfBirth < new DateTime(2006, 01, 01)))
        {
            Console.WriteLine(result.Name);
        }

    }
}

长颈鹿:

class Giraffe
{
    public Guid Id { get; set; }
    public string Name { get; set;  }
    public long Height { get; set; }
    public DateTime DateOfBirth { get; set; }
}

特殊情况,例如SingleAndDefault 等被排除在外。我想要工作的部分发生在迭代器中,它首先在执行字典之前执行列表的 QueryProvider。

两个 Queryable 对象之一可能是数据库或其他对象。

【问题讨论】:

  • 可以添加调用代码吗?
  • 您能否举例说明您用来调用 QueryProvider 的 Linq 表达式? (我正在尝试在本地重建您的代码)。另外,您是否也实现了通用版本的 Execute ? public TResult Execute&lt;TResult&gt;(System.Linq.Expressions.Expression expression) { ... }
  • 更新了 LINQ 表达式的示例以及 Query、QueryProvider 和 Collection 类中的其他代码。

标签: c# linq linq-expressions


【解决方案1】:

不,查询不会绑定到提供程序。这就是您拥有 IQueryable 接口的原因:它同时提供了表达式和提供程序,因此 LINQ 可以调用提供程序来执行表达式。

您的实现中的问题在于Query&lt;Entity&gt; 表示自身的方式:您将根表达式设置为Expression.Constant(this),其中this 是查询(不是集合)。

所以当你使用 LINQ-to-Objects 执行查询时,它会在 Query&lt;&gt; 上调用 GetEnumerator,然后调用 LINQ-to-Objects 来执行 Expression,它有一个根表达式 Expression.Constant(this)(类型为 Query&lt;&gt;),然后 LINQ-to-Objects 通过在此 Query&lt;&gt; 上调用 GetEnumerator 等来迭代此根表达式。

问题出在

(IEnumerable<Entity>)this.cacheOne.AsQueryable<Entity>().Provider.Execute(expression)

基本上等于

new Entity[0].AsQueryable().Provider.Execute(expression)

或

linqToObjectsProvider.Execute(expression)

查询返回的提供程序未链接到源 (this.cacheOne),因此您只是重新执行表达式,而不是查询缓存。

以下有什么问题?

class Collection<Entity>
{
    ...

    public IQueryable<Entity> Query()
    {
        return this.cacheOne.Concat(this.cacheTwo.Values).AsQueryable();
    }
}

请注意,Concat 使用延迟评估,因此只有在您执行查询时才将 cacheOne 和 cacheTwo 连接起来,然后使用附加的 LINQ 运算符进行操作。

(在这种情况下,我会将 Collection&lt;Entity&gt; 设为 IQueryablewithExpressionequal toExpression.Constant(this.cacheOne.Concat(this.cacheTwo.Values))`。我认为您可以取消所有其他类。)


原答案

但是,我认为这种捎带 LINQ to Objects 的方式永远无法完成您认为应该做的事情。

至少,您应该保留 原始 查询提供程序,以便在缓存未命中时调用该提供程序。如果您不这样做,并使用您自己的查询提供程序(您没有显示用于执行实际调用的代码),您的查询提供程序将一次又一次地调用自己。

所以你需要创建一个 CachingQueryProvider和一个 CachingQuery:

class CachingQuery<T> : IQueryable<T>
{
    private readonly CachingQueryProvider _provider;
    private readonly Expression _expression;

    public CachingQuery(CachingQueryProvider provider, Expression expression)
    {
        _provider = provider;
        _expression = expression;
    }

    // etc.
}

class CachingQueryProvider : IQueryProvider
{
    private readonly IQueryProvider _original;

    public CachingQueryProvider(IQueryProvider original)
    {
        _original = original;
    }

    // etc.
}

public static class CachedQueryable
{
    public static IQuerable<T> AsCached(this IQueryable<T> source)
    {
        return new CachingQuery<T>(
             new CachingQueryProvider(source.Provider), 
             source.Expression);
    }
}

另外,如果你想缓存一个结果,你需要在缓存它之前实现结果,否则你缓存的是查询,而不是结果。结果本身不应该再次执行,因为它已经是您应该返回的数据。

我的前进方向如下:

class CachingQueryProvider : IQueryProvider
{
    public object Execute(Expression expression)
    {
        var key = TranslateExpressionToCacheKey(expression);

        object cachedValue;
        if (_cache.TryGetValue(key, out cachedValue))
            return cachedValue;

        object result = _originalProvider.Execute(expression);

        // Won't compile because we don't know T at compile time
        IEnumerable<T> sequence = result as IEnumerable<T>;
        if (sequence != null && !(sequence is ICollection<T>)) 
        {
            result = sequence.ToList<T>();
        }

        _cache[key] = result; 

        return result;
    }
}

对于标记为Won't compile 的部分,您将不得不做一些反射技巧。

注意:字符串实现了 IEnumerable,所以要小心不要尝试实现单个字符串结果值。

【讨论】:

  • 谢谢鲁本,这很有帮助,但为什么你认为捎带 LINQ-to-Objects 永远不会做我希望的事情?你的解决方法很好,但我很好奇为什么你不觉得捎带可以工作。
  • LINQ to Objects 用于枚举内存中的集合(如数组)。这是它唯一能做的。因此,如果您让 LINQ to Objects 执行类似from entity in table where ... select entity 的查询,它将要求table 返回所有元素,然后将where 应用于结果。而table 将使用它自己的数据上下文来执行此操作(因此每次使用它时都会执行SELECT * FROM Table)。因此,您必须执行查询并将结果转换为内存结构并缓存它。我看不出 L2O 适合这里。
  • 另外IQueryProvider.Execute 应该总是返回查询的result。它不应返回中间表示。也许这就是混乱?
  • @Ruben IQueryProvider.PartialEval 可以在这种情况下使用吗?
  • @Totero 这可能是您需要计算缓存键的东西,因为查询表达式中的所有本地和字段都将由MemberExpressions 表示。或者我完全误解了原来的问题。我的训练是:如何缓存随机查询(每个不同的查询都有一个单独的缓存条目)。如果你想缓存完整的表但在内存中应用所有查询操作,你将需要一个不同的实现。
猜你喜欢
  • 1970-01-01
  • 2012-04-02
  • 2015-06-09
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-02-25
相关资源
最近更新 更多