返回 IQueryable<T>或不返回 IQueryable<T>
- 作者: 凉城薄梦轻眠47078792
- 来源: 51数据库
- 2022-10-28
问题描述
我有一个存储库类,用于包装我的 LINQ to SQL 数据上下文.存储库类是一个业务线类,包含所有数据层逻辑(以及缓存等).
I have a repository class that wraps my LINQ to SQL Data Context. The repository class is a business line class that contains all the data tier logic (and caching and such).
这是我的 repo 界面的 v1.
Here's my v1 of my repo interface.
public interface ILocationRepository
{
IList<Location> FindAll();
IList<Location> FindForState(State state);
IList<Location> FindForPostCode(string postCode);
}
但是为了处理 FindAll 的分页,我正在争论是否要公开 IQueryable
But to handle paging for FindAll, I'm debating whether or not to expose IQueryable<ILocation> instead of IList to simplify the interface for circumstances such as paging.
从数据存储库中公开 IQueryable 的利弊是什么?
What are the pros and cons to exposing IQueryable from the data repo?
非常感谢任何帮助.
推荐答案
优点;可组合性:
- 来电者可以添加过滤器
- 来电者可以添加分页
- 来电者可以添加排序
- 等
缺点;不可测试性:
- 您的存储库不再可正确进行单元测试;你不能依赖 a:它可以工作,b:它的作用是什么;
- 调用者可以添加不可翻译的函数(即没有 TSQL 映射;在运行时中断)
- 调用者可以添加一个过滤器/排序,使其表现得像一只狗
为了稳定性,我已经不在我的存储库中公开IQueryable
或Expression<...>.这意味着我知道存储库的行为方式,并且我的上层可以使用模拟而不必担心实际存储库是否支持这个?"(强制集成测试). For stability, I've taken to not exposing IQueryable<T> or Expression<...> on my repositories. This means I know how the repository behaves, and my upper layers can use mocks without worrying "does the actual repository support this?" (forcing integration tests).
我仍然使用 IQueryable
等inside 存储库 - 但不会超出边界.我发布了一些关于这个主题的更多想法.将分页参数放在存储库界面上同样容易.您甚至可以使用扩展方法(在接口上)添加可选分页参数,这样具体的类只有 1 个方法要实现,但调用者可能有 2 或 3 个可用的重载. I still use IQueryable<T> etc inside the repository - but not over the boundary. I posted some more thoughts on this theme here. It is just as easy to put paging parameters on the repository interface. You can even use extension methods (on the interface) to add optional paging parameters, so that the concrete classes only have 1 method to implement, but there may be 2 or 3 overloads available to the caller.
- C#通过fleck实现wss协议的WebSocket多人Web实时聊天(附源码)
- 团队城市未满足要求:MSBuildTools12.0_x86_Path 存在
- 使用 MSBuild.exe 在发布模式下构建 C# 解决方案
- 当我发布 Web 应用程序时,AfterPublish 脚本不运行
- 构建时 T4 转换的产品仅在下一个构建中使用
- ASP.NET Core Application (.NET Framework) for Windows x64 only error in project.assets.json
- 新的 .csproj 格式 - 如何将整个目录指定为“链接文件"到子目录?
- 如何将条件编译符号(DefineConstants)传递给 msbuild
- MSBuild 支持 Visual Studio 2017 RTM 中的 T4 模板
- NuGet 包还原找不到包,没有源
