Connecting nhibernate to Postgresql in C#

Mark picture Mark · Sep 3, 2015 · Viewed 7.4k times · Source

This is my first time working with nhibernate and I'm experiencing problems connecting and retrieving data from a Postgresql database. The code doesn't give an error, but returns no values either. When I use pgAdmin3 I do get data.

AutoPersistenceModel model = AutoMap.Assembly(System.Reflection.Assembly.GetCallingAssembly())
    .Where(t => t.Namespace == "POCPostgresql.Model");

var configuration = Fluently.Configure()
    .Database(PostgreSQLConfiguration.Standard
    .ConnectionString(c => c
        .Host("server")
        .Port(5432)
        .Database("database")
        .Username("username")
        .Password("password")))
    .Mappings(m => m
        .AutoMappings.Add(model))
    .ExposeConfiguration(config => new SchemaExport(config).Create(false, true))
    .BuildSessionFactory();

    using (var session = configuration.OpenSession())
    {
        // Query all objects
        var completeList = session.CreateCriteria<Object>().List();

        Console.ReadLine();
    }

The completelist variable is an empty list.

Is there anything I'm forgetting?

Edit: Also when moving the configuration to the app.config and initializing it differently results in an empty list

Configuration configuration = new Configuration();
configuration.Configure();
ApplicationCore.Instance.SessionFactory = configuration.BuildSessionFactory();

using (var session = ApplicationCore.Instance.SessionFactory.OpenSession())
{
    var completeList = session.CreateCriteria<Object>().List();

    Console.ReadLine();
}

Edit 2: I thought maybe it was the server that denies my query for some reason but I've tried querying using only npgsql, this is working fine.

NpgsqlConnection conn = new NpgsqlConnection("server=server;Port=5432;Database=database;User Id=username;Password=password;");
conn.Open();
string sql = "SELECT * FROM report LIMIT 100";

NpgsqlCommand command = new NpgsqlCommand(sql, conn);

NpgsqlDataReader dr = command.ExecuteReader();

while (dr.Read())
    Console.Write("{0}\t{1} \n", dr[0], dr[1]);

conn.Close();

Console.ReadLine();

Answer

Mark picture Mark · Sep 17, 2015

I've fixed this problem by changing the mapping to use fluent mappings and everything suddenly worked

.Mappings(m => m.FluentMappings.AddFromAssemblyOf<ReportDB>())