简体   繁体   English

列表<t>实现 IQueryable<t></t></t>

[英]List<T> to implement IQueryable<T>

I'm trying to create a mock for my IRepository interface:我正在尝试为我的IRepository接口创建一个模拟:

public interface IRepository<T> : ICollection<T>, IQueryable<T>
{
}

With this implementation:有了这个实现:

public class RepositoryFake<T> : List<T>, IRepository<T>
{
    public Expression Expression
    {
        get
        {
            return this.AsQueryable().Expression;
        }
    }

    public Type ElementType
    {
        get
        {
            return this.AsQueryable().ElementType;
        }
    }

    public IQueryProvider Provider
    {
        get
        {
            return this.AsQueryable().Provider;
        }
    }
}

But when I use it, I'm getting StackOverflow exception.但是当我使用它时,我得到了StackOverflow异常。 How to implement this interface correctly to be able to use just a List as a repository?如何正确实现此接口以便能够仅将List用作存储库?

Usage is very simple用法很简单

[Test]
public void Test()
{
    RepositoryFake<User> users = new RepositoryFake<User>();
    users.Add(new User());

    List<User> list = (from user in users 
                 where user.Id == "5"
                 select user).ToList();

    Assert.That(list, Is.Empty);
}

Here is screenshot of exception:这是异常的屏幕截图:

例外

The reason for your problem is that if you perform AsQueryable it checks if the object already implements IQueryable and if yes returns it.出现问题的原因是,如果您执行AsQueryable ,它会检查 object 是否已经实现IQueryable ,如果是则返回它。

Use new EnumerableQuery<T>(this) instead of AsQueryable which doesn't perform this check.使用new EnumerableQuery<T>(this)代替不执行此检查的AsQueryable


Workaround for .net 3.5: .net 3.5 的解决方法:

return ((IEnumerable<T>)this).Select(x=>x).AsQueryable()

First casts to IEnumerable<T> so the chosen Select method will be Enumerable.Select not Queryable.Select .首先转换为IEnumerable<T>所以选择的Select方法将是Enumerable.Select not Queryable.Select The identity select will then return a new object that does not implement IQueryable<T> , so the check if it's implemented in AsQueryable fails.身份 select 然后将返回一个新的 object ,它没有实现IQueryable<T> ,因此检查它是否在AsQueryable中实现失败。

Try using base.AsQueryable() instead of this.AsQueryable() .尝试使用base.AsQueryable()而不是this.AsQueryable()

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM