NHibernate - Why is connection needed to build factory if connection can be passed to session constructor?
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 开发者_如何学Cobject 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);
}
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.
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.
精彩评论