1

我想通过代码使用映射,所以我有一个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 元素设置资源,但找不到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);
            });
        }
    }
}
4

1 回答 1

0

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

NHibernate 3.2 代码映射——基本映射

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

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;
}
于 2015-09-22T13:56:10.343 回答