我首先尝试使用DDD和EF 4.1代码。我有一个聚合的根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个博客条目的标题和这些博客条目的评论数量。
目前,它的实现方式与下面类似:
foreach(BlogEntry be in blogEntryRepository.GetLatestBlogEntries())
{
string title = be.Title;
int amountOfComments = be.Comments.Count();
// display title, amountOfComments, ...
}不幸的是,实体框架在这里所做的是执行一个查询来获取BlogEntry对象,之后它对每个BlogEntry执行一个查询来检索注释的数量。
-> 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谢谢。
发布于 2011-08-23 19:14:18
我会选择更简单、更高效的方式--只需将NumberOfComments作为属性添加到BlogEntry上,在每个注释中递增它,并持久化它。基于aggregate有责任保持数据一致性这一事实。考虑到只显示数据的请求数量与实际更新的数量,我认为没有理由在每次有人想要查看它时计算这个数量。
发布于 2011-08-23 18:59:06
您可以这样做,但它将创建匿名类型,
var p= from a in db.BlogEntries
select new {a, a.Comments.Count};
var k = p.ToList(); 编辑..你可以这样做,
禁用延迟加载,将注释计数属性添加到blogEntry域类
public class BlogEntry
{
public int commentCount{
get
{
if(this.comments==null){
return this._commentCount
}else{
return this.Comments.count;
}
}
set{
this._commentCount=value;
}
}
//other properties...
}将新方法添加到存储库以获取所有注释计数,
var p= from a in db.BlogEntries
select new BlogEntry{Id=a.Id,CommentCount= a.Comments.Count , ect..};
var k = p.ToList();https://stackoverflow.com/questions/7159649
复制相似问题