0

我正在使用 NHibernate,我的要求是我有 2 个表,用户和票证。我想要用户中但不在票证中的所有记录。Ticket 表有 UserId 作为 User 表的主键 ID 的引用键。下面是我的代码,

 RegNotTickTemplate.Criteria = DetachedCriteria.For(typeof(User));
            RegNotTickTemplate.Criteria.Add(Subqueries.PropertyNotIn("ID",DetachedCriteria.For(typeof(Ticket))
                .SetProjection(Projections.Property("UserID"))));

上面的查询没有返回正确的记录集。

4

2 回答 2

0

What you are missing is: the count of tickets for this user should be greater than zero. Here is how you can implement it:

RegNotTickTemplate.Criteria = DetachedCriteria.For(typeof(User));
RegNotTickTemplate.Criteria.Add(Subqueries.PropertyIn("Id",
          DetachedCriteria.For<Ticket>()
            .SetProjection(Projections.GroupProperty("User"))
            .Add(Restrictions.Eq(Projections.RowCount(), 0))));

If you don't want the count of rows you can do the following:

RegNotTickTemplate.Criteria = DetachedCriteria.For(typeof(User),"user");
RegNotTickTemplate.Criteria.Add(Subqueries.Exists(DetachedCriteria.For<Ticket>("ticket")
            .SetProjection(Projections.Property("User"))
            .Add(Restrictions.EqProperty("user.Id", "User"))));
于 2012-06-27T06:55:11.467 回答
0

作为替代方案,您可以尝试使用 HQL。我从不使用 Criteria,因为我发现 HQL 更具可读性(它几乎与 SQL 相同,只是您可以根据实体而不是表进行查询)。

第 13 章 HQL:Hibernate 查询语言

IQuery query = Session.CreateQuery(
       "from User where Id not in (select UserId from Ticket)");
       query.List<User>();

如果还是不行,你可以随时进行 SQL 查询

ISQLQuery query = Session.CreateSQLQuery(sql);
于 2010-12-15T21:06:35.053 回答