返回 Enumerable.Empty().AsQueryable() 是一个坏主意吗?

发布于 2024-11-11 16:01:04 字数 565 浏览 3 评论 0原文

这可能最好用一些代码来解释:

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;
    }
}

这个想法是,如果没有当前HeldId可供查询,则没有理由再次实际查询数据库。如果 currentHeldIds 没有值,LINQ to SQL 仍将查询数据库。这种做法有什么问题吗?我意识到通常还有一些与返回 IQueryable 相关的问题,但除了这些论点之外,尝试像这样绕过数据库调用有什么问题吗?

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?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

做个ˇ局外人 2024-11-18 16:01:04

我认为你应该重新考虑你的函数实际上要做什么。如果您返回 IQueryable,则意味着调用者将存储结果查询,并在实际执行查询时收到最新结果。请记住:在这种情况下,直到 .ToList().ToArray()foreach 等被调用之前,数据库实际上不会被查询。在查询中调用。

但是,如果您的目标是返回查询的当前状态,那么您的方法应该只返回一个 IList 或类似的内容。然后,您可以返回一个空的 List,或者对您以其他方式构造并返回该查询的查询调用 .ToList()

一般来说,我会尽量避免返回空的可查询对象,因为它可能会误导调用者他们实际得到的内容。

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.

孤星 2024-11-18 16:01:04

对我来说似乎不错。如果功能与消费端相同,那应该是非常好的。

Seems fine to me. If the functionality is identical from the consuming side it should be perfectly good.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文