views:

119

answers:

2

I'm new to NHibernate and am attempting to use it to connect to DB2. After trial and error and research, and more trial and error and research, I've finally come down to an error to which I cannot find an answer.

The error message reads: "The user must provide an ADO.NET connection - NHibernate is not creating it."

This error is not very helpful. Does this mean that I need to 1) put a connection string in my config file or 2) do I need to pass the connection into the factory? If 1 is true, is this mandatory? If it is then why are we given the ability to pass the connection object into the session which is what I desire to do?

If 2) is true, how do I pass in a connection object into the factory?

Thank you in advance. Below are my code snippets which may be helpful:

<?xml version="1.0" encoding="utf-8" ?>
<configuration>
    <configSections>
        <section name="hibernate-configuration" type="NHibernate.Cfg.ConfigurationSectionHandler, NHibernate" />
    </configSections>
<hibernate-configuration xmlns="urn:nhibernate-configuration-2.2">
    <session-factory>
        <property name="dialect">NHibernate.Dialect.DB2400Dialect</property>
        <property name="proxyfactory.factory_class">NHibernate.ByteCode.Castle.ProxyFactoryFactory, NHibernate.ByteCode.Castle</property>
    </session-factory>
</hibernate-configuration>  
</configuration>

try
{               
    Configuration cfg = new Configuration();  

    cfg.AddInputStream(NHibernate.Mapping.Attributes.HbmSerializer.Default.Serialize(persistentClass));
    SessionFactory = cfg.Configure().BuildSessionFactory(); //HERE I GET THE EXCEPTION
}
catch (Exception ex)
{
    throw new Exception("NHibernate initialization failed", ex);
}
+1  A: 

You need the session factory for configuration like connections, what kind of mapping you use, what kind of caches you use, what kind of sql dialect, etc. Not just the connection, so passing a connection as constructor argument probably will give you another unhelpful exception. You have to setup the connection in your configuration.

Paco
I was trying to avoid putting my connection information in the config file so 1) it could not be seen in my WPF app by those snooping around and 2) so I could have the user type in the user id and password rather than hard coding it. Any ideas on getting around this? I may have to call the SetProperty method of the configuration object prior to calling BuildSessionFactory. Does that seem worthwhile or is there a better way? Thank You.
Brian
1. Do never use a shared database for multiple apps.2. If you really have to (when working on a legacy application) configuration.setproperty will work. I use fluentnhibernate for my configuration. That's much easier than xml.
Paco
A: 

If you look at the documentation you should be able to see how to create the session factory programaticaly. Alternatively you could use fluentNhibernate to avoid that configuration file.

Aaron Fischer