问题描述
假设我有一个简单的存储库类,其中有一个GetByNames
方法
Lets say I have a simple repository class, with one GetByNames
method
public class MyRepo
{
private readonly MyDbContext _db;
public MyRepo(MyDbContext db)
{
_db = db;
}
public IQueryable<MyObject> GetByNames(IList<string> names)
{
if (names== null || !names.Any())
{
return Enumerable.Empty<MyObject>().AsQueryable();
}
return _db.MyObjects.Where(a => names.Contains(a.Name));
}
}
现在,当我将其与异步EntityFramework ToListAsync()
扩展名一起使用
Now when I use it with async EntityFramework ToListAsync()
extension
var myObjects = awawit new MyRepo(_db).GetByNames(names).ToListAsync();
如果我传入空列表或null,因为Enumerable.Empty<MyObject>().AsQueryable()
未实现IDbAsyncEnumerable<MyObject>
接口,它将崩溃.
It will blow up if I pass in empty list or null because Enumerable.Empty<MyObject>().AsQueryable()
does not implement IDbAsyncEnumerable<MyObject>
interface.
所以我的问题是,如何在不访问数据库的情况下返回实现IDbAsyncEnumerable
的空IQueryable<>
?
So my question is, how can I return an empty IQueryable<>
that implements IDbAsyncEnumerable
, without hitting the database?
推荐答案
如果您不想访问数据库,则很可能必须提供自己的实现IDbAsyncEnumerable
的空IQuerable
实现.但我认为这并不难.在所有枚举器中,对于Current
仅返回null
,对于MoveNext
仅返回false
.在Dispose
中什么也不做.试试吧. Enumerable.Empty<MyObject>().AsQueryable()
与数据库无关,它绝对不实现IDbAsyncEnumerable
.根据此.
If you don't want to hit the DB, you'll most likely have to provide your own implementation of empty IQuerable
that implements IDbAsyncEnumerable
. But I don't think it is too hard. In all the enumerators just return null
for Current
and false
for MoveNext
. In Dispose
just do nothing. Try it. Enumerable.Empty<MyObject>().AsQueryable()
has nothing to do with database, it definitely does not implement IDbAsyncEnumerable
. You need an implementation that does, according to this.
这篇关于如何在异步存储库方法中返回空的IQueryable的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!