I have been seeing a lot of projects that have repositories that return instances of IQueryable. This allows additional filters and sorting can be performed on the IQueryable by other code, which translates to different SQL being generated. I am curious where this pattern came from and whether it is a good idea.
My biggest concern is that an IQueryable is a promise to hit the database some time later, when it is enumerated. This means that an error would be thrown outside of the repository. This could mean an Entity Framework exception is thrown in a different layer of the application.
I have also run into issues with Multiple Active Result Sets (MARS) in the past (especially when using transactions) and this approach sounds like it would lead to this happening more often.
I have always called ToList or ToArray at the end of each of my LINQ expressions to make sure the database is hit before leaving the repository code.
I am wondering if returning IQueryable could be useful as a building block for a data layer. I have seen some pretty extravagant code with one repository calling another repository to build an even bigger IQueryable.
whereclause to a deferredIQueryable, you only have to send that data over the wire, not the entire result set. – Robert Harvey Mar 26 '13 at 21:18IQueryablethat could wrap EF-specific exceptions for me. This would be fairly easy to write. – Travis Parks Mar 27 '13 at 13:00AsEnumerableisn't going to hit the database, it would just cast the object fromIQueryabletoIEnumerable, but the underlying structure would still beIQueryable(which means the SQL query has still not happened). – LionGod8 Nov 05 '23 at 12:45