Why use AsQueryable() instead of List()?

后端 未结 5 1656
傲寒
傲寒 2020-11-28 02:49

I\'m getting into using the Repository Pattern for data access with the Entity Framework and LINQ as the underpinning of implementation of the non-Test Repository. Most samp

5条回答
  •  醉话见心
    2020-11-28 03:42

    Returning IQueryable has the advantage, that the execution is defferer until you really start enumerating the result and you can compose the query with other queries and still get server side execution.

    The problem is that you cannot control the lifetime of the database context in this method - you need an open context and must ensure that it stays open until the query gets executed. And then you must ensure that the context will be disposed. If you return the result as a List, T[], or something similar, you loose deffered execution and server side execution of composed queries, but you win control over the lifetime of the database context.

    What fits best, of course, depends on the actual requirements. It's another question without a single truth.

提交回复
热议问题