c# - MVC 和存储库模式数据效率

标签 c# asp.net-mvc entity-framework performance

我的项目结构如下:

DAL

public IQueryable<Post> GetPosts()
{
        var posts = from p in context.Post select p;

        return posts;
}

服务

public IList<Post> GetPosts()
{
        var posts = repository.GetPosts().ToList();

        return posts;
}

//Returns a list of the latest feeds, restricted by the count.
public IList<PostFeed> GetPostFeeds(int latestCount)
{
       List<Post> post - GetPosts();

       //CODE TO CREATE FEEDS HERE

       return feeds;

}

假设 GetPostFeeds(5) 应该返回 5 个最新的提要。通过向上查找列表,它不是会从 GetPosts() 中从数据库中拉取每个帖子,只是为了从中提取 5 个帖子吗?

如果每个帖子都来自数据库 5kb,并且有 100 万条记录。每次调用 GetPostFeeds() 不会使用 5GB 内存吗?

事情就是这样发生的吗?我应该返回 DAL 并编写仅返回我需要的查询吗?

最佳答案

只要您使用 IQueryable,查询执行就可以延迟。一旦您调用 ToList() 或执行其他需要获取数据的操作(例如迭代子集合),就会执行查询。

我认为你不需要太担心你的 DAL,因为我喜欢让它们保持相当精简。不过,您可以通过重写 GetPostFeeds 方法来利用延迟执行,例如:

//Returns a list of the latest feeds, restricted by the count.
public IList<PostFeed> GetPostFeeds(int latestCount)
{
   var posts = repository.GetPosts();

   // Perform additional filtering here e.g:
   posts = posts.Take(5);

   return posts.ToList();
}

关于c# - MVC 和存储库模式数据效率,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2611451/

相关文章:

c# - 在 asp.net 中发送邮件

c# - 打开文件时,Excel 导入数据集会中断

c# - WPF 和 Flex 之间的区别

c# - 首先使用实体​​框架代码获取外键值

c# - 渲染没有 1-1 效果的图像

c# - 在 ASP.Net MVC 5 中使用 DataTables 行重新排序更新值

asp.net-mvc - 缓存的最佳解决方案

c# - 何时使用 API Controller 与 MVC Controller

c# - 为什么 ASP.NET Identity 的 `UserStore` 中有这么多存储库?

c# - Entity Framework OfType()