【发布时间】:2011-08-23 10:31:57
【问题描述】:
我正在尝试使用 DDD 和 EF 4.1 Code First。 我有一个 Aggregate Root BlogEntry,看起来与此类似:
public class BlogEntry
{
public long Id { get; set; }
public string Title { get; set;}
public string Content { get; set; }
public DateTime Created { get; set; }
public virtual ICollection<BlogEntryComment> Comments { get; set; }
}
现在,我想在一个门户网站中显示最近 10 个博客条目的标题以及这些博客条目的 cmets 数量。
目前的实现方式与此类似:
foreach(BlogEntry be in blogEntryRepository.GetLatestBlogEntries())
{
string title = be.Title;
int amountOfComments = be.Comments.Count();
// display title, amountOfComments, ...
}
不幸的是,Entity Framework 在这里所做的是执行一个查询以获取 BlogEntry 对象,然后为每个 BlogEntry 执行一个查询以检索 cmets 的数量。
-> EF 生成的 SQL 类似这样:
select top 10 * from BlogEntry order by Created desc
然后10次:
select count(*) from BlogEntryComment where BlogEntry = @blogEntryId
如何在不急于加载所有评论但仍不针对数据库对每个 BlogEntry 进行查询的情况下防止这种行为 - 但又不会与任何 DDD 规则发生冲突?
(我希望 EF 对数据库进行攻击是这样的:)
select top 10
be.*,
(select count(*) from BlogEntryComment c where c.BlogEntryId = be.Id) as AmountOfComments
from BlogEntry be order by be.Created DESC
谢谢。
【问题讨论】:
标签: c# entity-framework design-patterns domain-driven-design