Configuring Fluent NHibernate from NHibernate conf

2019-07-14 08:41发布

问题:

I'm trying to use Fluent NHibernate in my solution by configuring it with the following NHibernate xml configuration section

<hibernate-configuration  xmlns="urn:nhibernate-configuration-2.2" >
  <session-factory name="mitre">
    <property name="dialect">NHibernate.Dialect.Oracle9iDialect</property>
    <property name="connection.provider">NHibernate.Connection.DriverConnectionProvider</property>
    <property name="connection.driver_class">NHibernate.Driver.OracleDataClientDriver</property>
    <property name="connection.connection_string">Data Source=YOUR_DB_SERVER;Database=Northwind;User ID=YOUR_USERNAME;Password=YOUR_PASSWORD;</property>
    <property name="connection.isolation">ReadCommitted</property>
    <property name="default_schema">TRATE</property>
    <!-- HBM Mapping Files -->
    <mapping assembly="Markel.Mint.Mitre.Data" />
  </session-factory>
</hibernate-configuration>

In my code file, to instantiate ISession:

NH_Cfg.Configuration cfg = new NH_Cfg.Configuration();
cfg.Configure();

Fluently.Configure(cfg).Mappings(m => m.FluentMappings = ????)

My question is that if I have already specified the assembly in the NHibernate config section, do I need to explicitly set FluentMappings? If so, then is it possible to retrieve this data from NHibernate config programmatically?

Thanks Oz

回答1:

The mapping assembly in hibernate.cfg.xml is searched for embedded *.hbm.xml files. NHibernate does not know anything about fluent mappings (e.g. ClassMap) as those are introduced by Fluent NHibernate. So you need:

Fluently.Configure(cfg).Mappings(m => m.FluentMappings.AddFromAssemblyOf<SomeDomainType>();

in order to configure NHibernate using your ClassMap mappings.



回答2:

Thanks for the quick response, James.

Could I do the following then?

<?xml version="1.0" encoding="utf-8" ?>
<hibernate-configuration  xmlns="urn:nhibernate-configuration-2.2" >
  <session-factory name="mitre">
    <property name="dialect">NHibernate.Dialect.Oracle9iDialect</property>
    <property name="connection.provider">NHibernate.Connection.DriverConnectionProvider</property>
    <property name="connection.driver_class">NHibernate.Driver.OracleDataClientDriver</property>
    <property name="connection.connection_string">Data Source=YOUR_DB_SERVER;Database=Northwind;User ID=YOUR_USERNAME;Password=YOUR_PASSWORD;</property>
    <property name="connection.isolation">ReadCommitted</property>
    <property name="default_schema">TRATE</property>
    <property name="fluent.nhibernate.fluentmapping">Markel.Mint.Mitre.Core.Domain</property>
  </session-factory>
</hibernate-configuration>

Then my code could refer to the property thus:

NH_Cfg.Configuration cfg = new NH_Cfg.Configuration();  cfg.Configure();           
Fluently.Configure(cfg).Mappings(m => m.FluentMappings.AddFromAssembly(Assembly.Load(cfg.Properties["fluent.nhibernate.fluentmapping"])));