Search code examples
c#nhibernatefluent-nhibernatefluent

fluent nhibernate return column list when table is empty?


Is it possible to make FNH return columns with default values, in case when table is empty?

Here is a my code sample, it gets a database entity by the name:

    private IList<T> GetDictionaryListByName<T>(string dictionaryName)
    {
        IList<T> result = new T[0];
        using (var session = DbManager.SessionFactory.OpenSession())
        {
            result = session.QueryOver<IDictionary>(dictionaryName).List<T>();
        }

        return result;
    }

Solution

  • In case that QueryOver returns empty results, we can just return a new list with a new T(). We would need just few adjustments:

    private IList<T> GetDictionaryListByName<T>(string dictionaryName)
        where T : new() // passed T must have parameterless consctructor
    {
        using (var session = DbManager.SessionFactory.OpenSession())
        {
            var result = session
                 .QueryOver<IDictionary>(dictionaryName)
                 .List<T>();
    
            if(result.Any())   // if there is any result 
            {
                return result; // return that list
            }
        }
    
        return new List<T> {new T() }; // return new List with new T()
    }
    

    In case you would like to get more information about the T mapping, check this answer to your question (we can work with the AbstractEntityPersister to get column names...)