Returning Enumerable.Empty<T>().AsQueryable() a bad idea?
This is probably best explained with some code:
开发者_运维百科public IQueryable<DatabaseRecord> GetQueryableLinkedRecords()
{
if(this.currentlyHeldIds.Count() == 0)
{
return Enumerable.Empty<DatabaseRecord>().AsQueryable();
}
else
{
return from r in this.DBContext.DatabaseRecords
where this.currentlyHeldIds.Contains(r.Id)
select r;
}
}
The idea being that there's no reason to actually query the db again if there are no currentlyHeldId's to query on. LINQ to SQL will still query the db if currentlyHeldIds has no values. Is there anything wrong with this approach? I realize there are some other concerns related to returning IQueryable in general, but those arguments aside, is there anything wrong with trying to circumvent the db call like this?
I think you should rethink about what your function is actually going to do. If you're returning an IQueryable<T>
, then the implication is that callers will store the resulting query, and will receive up-to-date results when they actually execute the query. Remember: the database won't actually be queried in this case until .ToList()
, .ToArray()
, foreach
, etc. is invoked on the query.
If your goal, though, is to return the current state of the query, then your method should just return an IList<T>
or something along those lines. Then, you can either return an empty List<T>
, or call .ToList()
on the query you otherwise construct and return that.
In general, I would try to avoid returning empty queryables, since it can mislead callers about what they are actually getting.
Seems fine to me. If the functionality is identical from the consuming side it should be perfectly good.
精彩评论