NHibernate:LINQ to NHibernate自连接

时间:2016-07-29 08:48:02

标签: sql nhibernate linq-to-nhibernate

我尝试使用LINQ to NHibernate实现以下SQL语句:

SELECT a.JOB_ID ID FROM SERVICE_DATA a WHERE STEP_ID = x and (STATUS = 'Success' or STATUS = 'Skipped') 
  AND a.JOB_ID not in (SELECT JOB_ID FROM SERVICE_DATA WHERE JOB_ID = a.JOB_ID AND STATUS = 'Error') 
  AND a.JOB_ID not in (SELECT JOB_ID FROM SERVICE_DATA WHERE STEP_ID = y and (STATUS = 'Success' or STATUS = 'Skipped' or STATUS = 'Error'));

目前,我可以使用以下方式选择期望第一个NOT IN自连接条件的所有内容:

DetachedCriteria secondSubCriteria = DetachedCriteria.For<ServiceData>()
            .SetProjection(Projections.Property("JobId"))
            .Add(Restrictions.Eq("StepId", stepId))
            .Add(Restrictions.Disjunction()
                .Add(Restrictions.Eq("Status", "Success"))
                .Add(Restrictions.Eq("Status", "Skipped"))
                .Add(Restrictions.Eq("Status", "Error")));

var data = session.CreateCriteria<ServiceData>()
                .Add(Restrictions.Eq("StepId", stepId))
                .Add(Restrictions.Disjunction()
                    .Add(Restrictions.Eq("Status", "Success"))
                    .Add(Restrictions.Eq("Status", "Skipped")))
              //.Add(Subqueries.PropertyNotIn("JobId", ???))
                .Add(Subqueries.PropertyNotIn("JobId", secondSubCriteria))
                .List<ServiceData>()
                .Take(1)
                .FirstOrDefault();

如何根据列JOB_ID获取自连接以处理示例中的第一个子标准?

1 个答案:

答案 0 :(得分:0)

尝试后我自己找到了答案,因为任何有相同问题的人在Criteria()构造函数中指定了一个表别名,并在其他查询中引用它。

 DetachedCriteria firstSubCriteria = DetachedCriteria.For<ServiceData>("x")
        .SetProjection(Projections.Property("x.JobId"))
        .Add(Restrictions.EqProperty("x.JobId", "s.JobId"))
        .Add(Restrictions.Not(Restrictions.Eq("x.Status", "Error")));

 DetachedCriteria secondSubCriteria = DetachedCriteria.For<ServiceData>()
        .SetProjection(Projections.Property("JobId"))
        .Add(Restrictions.Eq("StepId", stepId))
        .Add(Restrictions.Disjunction()
            .Add(Restrictions.Eq("Status", "Success"))
            .Add(Restrictions.Eq("Status", "Skipped"))
            .Add(Restrictions.Eq("Status", "Error")));  

var data = session.CreateCriteria<ServiceData>("s")
        .Add(Restrictions.Eq("StepId", stepId))
        .Add(Restrictions.Disjunction()
             .Add(Restrictions.Eq("s.Status", "Success"))
             .Add(Restrictions.Eq("s.Status", "Skipped")))
        .Add(Subqueries.PropertyNotIn("s.JobId", firstSubCriteria))
        .Add(Subqueries.PropertyNotIn("s.JobId", secondSubCriteria))
        .List<ServiceData>()
        .Take(1)
        .FirstOrDefault();