Logo

NHibernate

The object-relational mapper for .NET

How to

This page is converted from the old nhforge.org Wiki. Published by: Ricardo Peres on 11-18-2011

Checking if an Unloaded Collection Contains Elements

If you want to know if an unloaded collection in an entity contains elements, or count them, without actually loading them, you need to use a custom query; that is because the Count property (if the collection is not mapped with lazy=”extra”) and the LINQ Count() andAny() methods force the whole collection to be loaded.

You can use something like these two methods, one for checking if there are any values, the other for actually counting them:

 

public static Boolean Exists(this ISession session, IEnumerable collection)
{
     if (collection is IPersistentCollection)
     {
         IPersistentCollection col = collection as IPersistentCollection;
  
         if (col.WasInitialized == false)
         {
                 String[] roleParts = col.Role.Split('.');
                 String ownerTypeName = String.Join(".", roleParts, 0, roleParts.Length - 1);
                 String ownerCollectionName = roleParts.Last();
                 String hql = "select 1 from " + ownerTypeName + " it where it.id = :id and exists elements(it." + ownerCollectionName + ")";
                 Boolean exists = session.CreateQuery(hql).SetParameter("id", col.Key).List().Count == 1;
  
                 return (exists);
         }
     }
  
     return ((collection as IEnumerable).OfType<Object>().Any());
 }
  
public static Int64 Count(this ISession session, IEnumerable collection)
{
    if (collection is IPersistentCollection)
    {
        IPersistentCollection col = collection as IPersistentCollection;
 
        if (col.WasInitialized == false)
        {
            String[] roleParts = col.Role.Split('.');
            String ownerTypeName = String.Join(".", roleParts, 0, roleParts.Length - 1);
            String ownerCollectionName = roleParts.Last();
            String hql = "select count(elements(it." + ownerCollectionName + ")) from " + ownerTypeName + " it where it.id = :id";
            Int64 count = session.CreateQuery(hql).SetParameter("id", col.Key).UniqueResult<Int64>();
 
            return (count);
        }
    }
 
    return ((collection as IEnumerable).OfType<Object>().Count());
}

Here's how:

MyEntity entity = session.Load(100);

if (session.Exists(entity.SomeCollection))
{
    Int32 count = session.Count(entity.SomeCollection);
    //...
}

 

 

© NHibernate Community 2016