NHibernate选择查询

时间:2014-03-10 15:36:03

标签: .net linq nhibernate

我有以下问题:

public IList<Category> GetLeafCategories()
{
    // select all categories that are not ParentCategory
    string sqlQuery =  @"
    select * from Catalog_Categories c
    where c.CategoryId not in (
        select distinct ParentCategoryId 
        from Catalog_Categories)
    ";

    //
    // I need an equivalent nHibernate query
    //
    var categs = NHibernateSession.Current.Query<Category>();
    IQueryable<Category> leafCategs = from cat in categs
                                      where cat.Id not in // HOW TO???
                                          (from c in categs 
                                           select c.ParentCategory.Id)
                                        select cat;
    return leafCategs.ToList();
}

2 个答案:

答案 0 :(得分:2)

我没有对此进行测试,但它应该有效:

var session = NHibernateSession.Current;

var subquery = session.Query<Category>
    .Select(x => x.ParentCategory.Id);

return session.Query<Category>
    .Where(x => !subquery.Contains(x.Id))
    .ToList();

答案 1 :(得分:0)

var categs = NHibernateSession.Current.Query<Category>();
IQueryable<Category> leafCategs = from cat in categs
                                  let parentIds = 
                                      (from c in categs 
                                       select c.ParentCategory.Id)
                                  where !parentIds.Any( p => p == cat.Id)
                                 select cat;

你可以像上面那样做。