需要NHibernate Criteria API帮助

时间:2011-06-29 18:32:41

标签: nhibernate criteria-api

我正在尝试创建一个条件查询,该查询通过useruploaded抓取“RejectedRecords”但未标记为已删除,或者RejectedRecord中的Facility位于用户被分配到的设施列表中(user.UserFacilities)。我有第一部分工作正常(按用户和未删除),但我不知道如何添加OR子句来获取用户设施集合中的记录。在SQL中它看起来像:

SELECT * 

FROM RejectedRecords

WHERE (UserUploaded = 1 AND IsDeleted = 0) 
OR FacilityId IN (SELECT FacilityId FROM UserFacility WHERE UserId = 1)

这是我在C#中的尝试(不确定如何执行子查询):

    public IList<RejectedRecord> GetRejectedRecordsByUser(User u)
    {
        return base._session.CreateCriteria(typeof(RejectedRecord))
            .Add(
                    (
                        Expression.Eq(RejectedRecord.MappingNames.UserUploaded, u)
                        && Expression.Eq(RejectedRecord.MappingNames.IsDeleted, false)

                    )
            )
            .List<RejectedRecord>();
    }

1 个答案:

答案 0 :(得分:3)

关键是将Disjunction and Conjunction与子查询结合使用。

var facilityIdQuery = DetachedCriteria.For<UserFacility>()
   .Add(Expression.Eq("User.Id", u))
   .SetProjection(Projections.Property("Facility.Id"));

var results = session.CreateCriteria<RejectedRecords>()
    .Add(
        Restrictions.Disjunction()
        .Add(
            Restrictions.And(
              Restrictions.Eq(RejectedRecord.MappingNames.UserUploaded, u),
              Restrictions.Eq(RejectedRecord.MappingNames.IsDeleted, false)
            )
        )
        .Add(Subqueries.PropertyIn("FacilityId",facilityIdQuery))
    ).List();