我使用QueryOver进行下一个Fluent NHibernate查询:
IQueryOver<Task> query = session
.QueryOver<Task>()
.JoinAlias(x => x.Subject, () => subject, JoinType.LeftOuterJoin)
.JoinAlias(() => subject.Localizations, () => localization, JoinType.LeftOuterJoin)
.Where(() => localization.Language.Id == languageId || localization.Language.Id == null);
.Where(x => x.UserId == userId)
执行下一个查询:
SELECT * FROM Tasks left outer join Subjects on Tasks.SubjectId = Subjects.IdAsignatura
left outer join Languages on Subjects.SubjectId=Languages.SubjectId
WHERE Tasks.UserId = xxx
and (Languages.LanguageId = yyy or Languages.LanguageId = is null)
我想避免使用“LEFT OUTER JOIN ... AND”这样的最后一行:
SELECT * FROM Tasks left outer join Subjects on Tasks.SubjectId = Subjects.IdAsignatura
left outer join Languages on Subjects.SubjectId=Languages.SubjectId AND Languages.LanguageId = yyy
WHERE Tasks.UserId = xxx
有没有办法执行“LEFT OUTER JOIN ... AND”Fluent NHibernate查询?
答案 0 :(得分:2)
CreateAlias有一个重载:
/// <param name="path">Lambda expression returning association path</param>
/// <param name="alias">Lambda expression returning alias reference</param>
/// <param name="joinType">Type of join</param>
/// <param name="withClause">Additional criterion for the SQL on clause</param>
/// <returns>
/// criteria instance
/// </returns>
IQueryOver<TRoot, TSubType> JoinAlias<U>(Expression<Func<U>> path
, Expression<Func<U>> alias, JoinType joinType
, ICriterion withClause);
这意味着,我们可以将WHRE中的限制传递给ON子句
/// instead of this
.JoinAlias(() => subject.Localizations, () => localization, JoinType.LeftOuterJoin)
.Where(() => localization.Language.Id == languageId
|| localization.Language.Id == null);
/// We can use this:
.JoinAlias(() => subject.Localizations, () => localization, JoinType.LeftOuterJoin
// the 4th param is appended to ON clause with AND operator
, Restrictions.Where(() => localization.Language.Id == languageId)
)
可以将 withClause 注入SELECT的ON部分,但始终使用AND运算符。因此,它只能应用更多限制而不是基本映射关系。