我有以下型号:
public class User
{
public virtual int Id { get; set; }
public virtual string Username { get; set; }
public virtual string Password { get; set; }
public virtual string Email { get; set; }
public IList<SubmissionNote> Notes { get;set; }
}
public class SubmissionNote
{
public virtual Int64 Id { get; set; }
public virtual string Text { get; set; }
public virtual DateTime CreatedOn { get; set; }
public virtual User Creator { get; set; }
public virtual Submission BelongsTo { get; set; }
}
public class Submission
{
public virtual Int64 Id { get; set; }
public virtual DateTime HappenedOn { get; set; }
public virtual int StatusCode { get; set; }
}
我想编写一个查询,其中包含一些用户输入最后一个注释的所有提交内容或用户名列表(由其名称标识)。感谢您使用NHibernate QueryOver API构建此查询的帮助。我已经能够创建一个查询来将所有最后的注释带到如下:
SubmissionNote alias = null;
var lastNote = session.QueryOver<SubmissionNote>()
.SelectList(list => list.
SelectGroup(x => x.BelongsTo).WithAlias(() => alias.BelongsTo).
SelectMax(x => x.CreatedOn).WithAlias(() => alias.CreatedOn).
Select(x => x.Creator).WithAlias(() => alias.Creator).
Select(x => x.Id).WithAlias(() => alias.Id).
Select(x => x.Text).WithAlias(() => alias.Text))
.TransformUsing(Transformers.AliasToBean<SubmissionNote>())
.List();
我可以使用指定的查询作为子查询来生成所需的结果吗?或者你建议另一个解决方案?
答案 0 :(得分:3)
我会尝试使用子查询这样的东西(虽然没有经过测试)
SubmissionNote subNoteAlias = null, subNoteAliasMax =null;
User userAlias = null;
String[] userNames = new[]{"John","Joe"};
var subquery =
QueryOver.Of(() => subNoteAliasMax)
.Where(subNote => subNote.BelongsTo.Id == subNoteAlias.BelongsTo.Id)
.Select(Projections.Max<SubmissionNote>(subNote => subNote.CreatedOn));
var result = session
.QueryOver<SubmissionNote>(() => subNoteAlias)
.WithSubquery.WhereProperty(subNote=>subNote.CreatedOn).Eq(subquery)
.JoinQueryOver(
subNote=>subNote.Creator
,()=>userAlias
,JoinType.InnerJoin
,Restrictions.In(Projections.Property(() => userAlias.Username ), userNames))
.List();
生成的SQL查询(非常)大致如下:
SELECT SubmissionNote.*
FROM SubmissionNote INNER JOIN User
ON SubmissionNote.creatorId = User.userId
AND User.userName in ('john','joe')
WHERE SubmissionNote.CreatedOn = (SELECT MAX(CreatedOn) FROM SubmissionNote snAlias
WHERE snAlias.SubmissionId = SubmissionNote.SubmissionId)
希望这会有所帮助。子查询可能存在问题,返回日期而不是id。 LMK和我会看看。