我的项目结构如下:
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/