[英]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.