Check if object exists in database without loading object with NHibernate

Viewed 18930

Is there a way in NHibernate to check if an object exists in the database without having to get/load the object?

9 Answers

I created an extension method from the answers above. I choose to use the Any version but with a Select on the primary key the same amount of data will be returned depend on the primary key type.

public static bool Exists<TModel, TKey>(
    this IQueryable<TModel> query, Expression<Func<TModel, TKey>> selector, TKey id)
    where TKey : class
{
    return query
        .Select(selector)
        .Any(x => x == id);
}

public static Task<bool> ExistsAsync<TModel, TKey>(
    this IQueryable<TModel> query, Expression<Func<TModel, TKey>> selector, TKey id)
    where TKey : class
{
    return query
        .Select(selector)
        .AnyAsync(x => x == id);
}
Related