通过代码使用Nhibernate映射时在配置文件中进行映射

时间:2015-09-22 13:16:51

标签: nhibernate mapping-by-code nhibernate-configuration conform

我想按代码使用映射,因此我有一个类 Employee namespace NHibernateTests.Classes)和一个类 EmployeeMappings namespace NHibernateTests.Mappings

我的整个nhibernate配置是在xml文件hibernate.cfg.xml中设置的,目前是这样的:

<?xml version="1.0" encoding="utf-8" ?>
<hibernate-configuration xmlns="urn:nhibernate-configuration-2.2">
  <session-factory>
    <property name="connection.provider">NHibernate.Connection.DriverConnectionProvider</property>
    <property name="connection.driver_class">NHibernate.Driver.OracleClientDriver</property>
    <property name="connection.connection_string">User Id=NHIBERNATE;Password=NHIBERNATE;Data Source=XE</property>
    <property name="show_sql">false</property>
    <property name="dialect">NHibernate.Dialect.Oracle10gDialect</property>

    <mapping assembly="NHibernateTests"/>
  </session-factory>
</hibernate-configuration>

这给了我运行时错误:没有持久性:NHibernateTests.Classes.Employee

我尝试(和错误)mapping元素的一些设置,但没有运气。我读了如何为hbm.xml元素设置ressource但是找不到by code映射的答案。

namespace NHibernateTests.Classes
{
    public class Employee
    {
        public virtual Address Address { get; set; }
        public virtual string FirstName { get; set; }
        public virtual int Id { get; set; }
    }
}


namespace NHibernateTests.Mappings
{
    public class EmployeeMappings : ClassMapping<Employee>
    {
        public EmployeeMappings()
        {
            this.Id(e => e.Id, mapper =>
            {
                mapper.Generator(Generators.HighLow);
            });
        }
    }
}

1 个答案:

答案 0 :(得分:0)

通过代码映射,您还应该按代码配置工厂。有一个方法是:

NHibernate 3.2 Mapping by Code – Basic Mapping

引用的代码段(有关详细信息,请参见上面的链接)

private static Configuration ConfigureNHibernate()
{
  var configure = new Configuration();
  configure.SessionFactoryName("BuildIt");

  configure.DataBaseIntegration(db =>
  {
    db.Dialect();
    db.Driver();
    db.KeywordsAutoImport = Hbm2DDLKeyWords.AutoQuote;
    db.IsolationLevel = IsolationLevel.ReadCommitted;

    db.ConnectionStringName = "NH3";
    db.Timeout = 10;

    // enabled for testing
    db.LogFormattedSql = true;
    db.LogSqlInConsole = true;
    db.AutoCommentSql = true;
  });

  var mapping = GetMappings();
  configure.AddDeserializedMapping(mapping, "NHSchemaTest");
  SchemaMetadataUpdater.QuoteTableAndColumns(configure);

  return configure;
}

如何获得HbmMapping

的方法
private static HbmMapping GetMappings()
{
  var mapper = new ModelMapper();

  mapper.AddMappings(Assembly.GetAssembly(typeof(ProvinceMap)).GetExportedTypes());
  var mapping = mapper.CompileMappingForAllExplicitlyAddedEntities();

  return mapping;
}