NHibernate - 左连接

时间:2012-02-15 12:31:24

标签: nhibernate join left-join outer-join

我有以下两个表:

作业 AreaID,JobNo(复合键)

记录 LogID,AreaID,JobNo

我需要获取所有没有与之关联的日志的作业。在SQL中,我可以这样做:

SELECT Jobs.AreaID,
       Jobs.JobNo
FROM   Jobs
       LEFT JOIN Logs
           ON Jobs.AreaID = Logs.AreaID
           AND Jobs.JobNo = Logs.JobNo
WHERE  Logs.LogID is null

但我不知道如何用NHibernate来实现这个目标。任何人都可以提供任何指示吗?

以下是我的映射:

<class name="Job" table="Jobs">
    <composite-key name="Id">
        <key-property name="JobNo"/>
        <key-many-to-one name="Area" class="Area" column="AreaID"/>
    </composite-key>
</class>

<class name="Log" table="Logs">
    <id name="Id" column="LogID">
        <generator class="identity"/>
    </id>
    <property name="JobNo"/>
    <many-to-one name="Area" class="Area" column="AreaID"/>
</class>

由于

更新

好的,我稍微修改了诺西拉的答案,现在正在做我想要的事情:

Log logs = null;

return session.QueryOver<Job>()
    .Left.JoinAlias(x => x.Logs, () => logs)
    .Where(x => logs.Id == null)
    .List<Job>();

我还必须将此添加到我的作业映射中:

<bag name="Logs">
    <key>
        <column name="JobNo"></column>
        <column name="DivisionID"></column>
    </key>
    <one-to-many class="Log"/>
</bag>

感谢您的帮助。 :)

2 个答案:

答案 0 :(得分:6)

我不熟悉复合标识符,因为我不使用它们,所以我知道NHibernate将自动创建正确的左连接。尽管如此,下面的(未经测试的)查询应该可以帮助您入门。

Job jobAlias = null;
Log logAlias = null;
YourDto yourDto = null;

session.QueryOver<Job>()
    // Here is where we set what columns we want to project (e.g. select)
    .SelectList(x => x
        .Select(x => x.AreaID).WithAlias(() => jobAlias.AreaID)
        .Select(x => x.JobNo).WithAlias(() => jobAlias.JobNo)
    )
    .Left.JoinAlias(x => x.Logs, () => logAlias, x.JobNo == logAlias.JobNo)
    .Where(() => logAlias.LogID == null)
    // This is where NHibernate will transform what you have in your `SelectList()` to a list of objects
    .TransformUsing(Transformers.AliasToBean<YourDto>())
    .List<YourDto>();

public class YourDto
{
    public int AreaID { get; set; }
    public int JobNo { get; set; }
}

注意:您需要NHibernate 3.2才能设置连接条件。

答案 1 :(得分:4)

Job job = null;
var jobsWithoutLogs = session.QueryOver(() => job)
    .WithSubquery.WhereNotExists(QueryOver.Of<Log>()
        .Where(log => log.Job == job)
        .Select(Projections.Id()))
    .List()

更新:我看到你添加了映射。以上代码仅适用于以下映射

<class name="Log" table="Logs">
    <id name="Id" column="LogID">
        <generator class="identity"/>
    </id>
    <many-to-one name="Job" >
      <column name="JobNo"/>
      <column name="AreaID"/>
    <many-to-one />
</class>