serhio
serhio

Reputation: 28586

NHibernate select query

I have the following problem:

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();
}

Upvotes: 0

Views: 1556

Answers (2)

Onur Gumus
Onur Gumus

Reputation: 1439

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;

You can do it like above.

Upvotes: 0

Najera
Najera

Reputation: 2879

Im not tested this, but it should work:

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();

Upvotes: 2

Related Questions