我有两个有父子关系的表。我想计算子表的记录,由父实体对它们进行分组并收集结果。所以我想看看在子表中引用每个父实体的次数。
所以如果我的父表是Cats:
| Id | Name |
| 1 | Bob |
| 2 | Garfield |
并且子表是CatSkills:
| Id | Cat_Id | Skill |
| 1 | 1 | Land on feet |
| 2 | 2 | Eat lasagne |
| 3 | 2 | Escape diets |
我想收到这个:
| Id | Name | count of skills |
| 1 | Bob | 1 |
| 2 | Garfield | 2 |
我已尝试使用NHibernate LINQ,查询似乎是正确的,但我得到了“不支持的功能”异常。
我尝试使用NHibernate QueryOver,在那里我遇到了N + 1问题:
var q = Session.QueryOver<CatSkill>()
.Fetch(s => s.Cat).Eager
.Select(Projections.ProjectionList()
.Add(Projections.Group<CatSkill>(s => s.Cat))
.Add(Projections.RowCount()))
.List<object[]>();
上述查询有效但会在不同的查询中获取所有父记录。
在实验我结束了有关在SELECT语句中引用的列怎么不是GROUP BY子句的一部分SQL异常的其他部分。
有没有人知道如何实现此查询?谢谢!
更新
感谢Radim,更新后的代码如下所示:
// a private class, just to make the query work
class CatDto : Cat
{
public int Count { get; set; }
}
// the actual query code
Cat parent = null;
CatSkill child = null;
CatDto dto = null;
// this is in fact a subselect, which will be injected into parent's SELECT
var subQuery = QueryOver.Of<CatSkill>(() => child)
.Where(() => child.Cat.ID == parent.ID)
.Select(Projections.RowCount());
// this is another subquery to filter out cats without skills
var skillFilterSubQuery = QueryOver.Of<CatSkill>(() => child)
.Where(() => child.Cat.ID == parent.ID /* && more criteria on child table here... */)
.Select(p => p.Cat);
// the alias here is essential, because it is used in the subselect
var query = session.QueryOver<Cat>(() => parent);
// I only want cats with skills
query = query.WithSubquery.WhereExists(skillFilterSubQuery);
query.SelectList(l => l
.Select(p => p.ID).WithAlias(() => dto.ID)
.Select(p => p.Name).WithAlias(() => dto.Name)
// annoying part: I have to repeat the property mapping for all needed properties of parent...
// see the parent.Count property
.Select(Projections.SubQuery(subQuery)).WithAlias(() => dto.Count));
query.TransformUsing(Transformers.AliasToBean<CatDto>());
return query.List<CatDto>();
因此,这摆脱了N + 1个的问题,但我必须(在本例猫)的父类的每个属性手动映射到DTO。
这将是很好如果像.Select(s => s)
,但抛出异常说,它不能映射“”属性我可以映射。
答案 0 :(得分:3)
一种优雅的方式可以是直接查询父Cat
,并使用所需的计数扩展它 - 作为子选择。
Cat parent = null;
CatSkills child = null;
// this is in fact a subselect, which will be injected into parent's SELECT
var subQuery = QueryOver.Of<CatSkills>(() => child)
.Where(() => child.Cat.ID == parent.ID)
.Select(Projections.RowCount());
// the alias here is essential, because it is used in the subselect
var query = session.QueryOver<Cat>(() => parent);
query.SelectList(l => l
.Select(p => p.ID).WithAlias(() => parent.ID)
.Select(p => p.Name).WithAlias(() => parent.Name)
// see the parent.Count property
.Select(Projections.SubQuery(subQuery)).WithAlias(() => parent.Count)
);
query.TransformUsing(Transformers.AliasToBean<Cat>());
所以在这种情况下,我们确实希望,Parent确实有一个属性
public virtual int Count { get; set ;}
未由NHiberante映射。如果我们无法扩展C#对象,我们可以创建一些CatDTO
(具有与Cat
实体相同的属性 - 加上Count
)