What exactly does IQueryable mean?

余生颓废 提交于 2021-01-22 08:28:18

问题


I'm not sure I understand what exactly IQueryable is.

I understand that it doesn't get me all the entities and puts the constraint part in memory but executes it as part of the command it sends to the database.

Please correct me if I'm mistaken and tell me, why should my repository functions return IQueryable and not a simple List?


回答1:


An IQueryable is not actually a collection of entities, rather it describes how to obtain that collection. The data is never retrieved from the source until you evaluate it, by turning it into an IEnumerable or something similar.

The advantage of returning an IQueryable from your repository is that your calling code can specify additional .Where clauses BEFORE the query goes to the database. If you returned an IEnumerable, your code would retrieve all values of one table from the database, and then perform filtering in memory, which is inefficient.




回答2:


IQueryable and IQueryable<T> are abstractions that encapsulate LINQ expressions; these expressions are then used by a LINQ provider - like the one used by Entity Framework - to turn these expressions into SQL that will, in turn, be sent to the database. Different LINQ providers interpret LINQ expressions differently, for example, MongoDB's turns these expressions into JSON queries.

IQueryables are only evaluated when a "terminal" method is called upon them, like, ToList(), ToArray(), Single(), SingleOrDefault(), First(), FirstOrDefault(), Count(), Any(), etc. This is when the provider quicks in and does the translation. Microsoft includes a LINQ provider, which does not do a translation to anything, but operates in memory. This is the one used when you turn an IEnumerable<T> into an IQueryable<T>, by calling the extension method AsQueryable().



来源:https://stackoverflow.com/questions/35542005/what-exactly-does-iqueryable-mean

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!