如何计算关联实体而不在实体框架中获取它们 [英] How To Count Associated Entities Without Fetching Them In Entity Framework

查看:319
本文介绍了如何计算关联实体而不在实体框架中获取它们的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我一直想知道这一段时间,所以我认为这是值得使用我的第一个Stack Overflow的帖子来询问它。

I've been wondering about this one for a while now, so I thought it would be worth using my first Stack Overflow post to ask about it.

想象一下我有一个与相关邮件列表的讨论:

Imagine I have a discussion with an associated list of messages:

DiscussionCategory discussionCategory = _repository.GetDiscussionCategory(id);

讨论类别。讨论是当前未加载的讨论实体的列表。

discussionCategory.Discussions is a list of Discussion entities which is not currently loaded.

我想要的是能够通过讨论类别中的讨论迭代,并说明每个讨论中有多少个消息,而无需提取消息数据。

What I want is to be able to iterate through the discussions in a discussionCategory and say how many messages are in each discussion without fetching the message data.

当我在尝试加载讨论和消息之前,我可以这样做:

When I have tried this before I have had to load the Discussions and the Messages so that I could do something like this:

discussionCategory.Discussions.Attach(Model.Discussions.CreateSourceQuery().Include("Messages").AsEnumerable());

foreach(Discussion discussion in discussionCategory.Discussions)
{

int messageCount = discussion.Messages.Count;

Console.WriteLine(messageCount);

}

这看起来效率低下,来自数据库的消息体,并将它们保存在内存中,当我想做的是计数他们的数字为演示目的。

This seems rather inefficient to me as I am fetching potentially hundreds of message bodies from the database and holding them in memory when all I wish to do is count their number for presentational purposes.

我已经看到一些问题触及这个问题但他们似乎没有直接解决。

I have seen some questions which touch on this subject but they did not seem to address it directly.

感谢您对此主题的任何想法。

Thanks in advance for any thoughts you may have on this subject.

更新 - 根据请求提供一些其他代码:

Update - Some more code as requested:

public ActionResult Details(int id)
    {  
        Project project = _repository.GetProject(id);
        return View(project);
    }

然后在视图(只是为了测试):

Then in the view (just to test it out):

Model.Discussions.Load();
var items = from d in Model.Discussions select new { Id = d.Id, Name = d.Name, MessageCount = d.Messages.Count() };

foreach (var item in items) {
//etc



<我希望这使我的问题有点更清楚。如果您需要更多代码详细信息,请与我们联系。

I hope that makes my problem a bit clearer. Let me know if you need any more code details.

推荐答案

只需将项目更改为POCO(或匿名)类型:

Easy; just project onto a POCO (or anonymous) type:

var q = from d in Model.Discussions
        select new DiscussionPresentation
        {
            Subject = d.Subject,
            MessageCount = d.Messages.Count(),
        };

当你查看生成的SQL,你会看到 Count ()是由DB服务器完成的。

When you look at the generated SQL, you'll see that the Count() is done by the DB server.

注意,这在EF 1和EF 4中都有效。

Note that this works in both EF 1 and EF 4.

这篇关于如何计算关联实体而不在实体框架中获取它们的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆