为什么FluentNhibernate为现有行返回NullReference?

时间:2011-04-13 08:32:07

标签: nhibernate fluent-nhibernate primary-key nullreferenceexception

我没有从此设置中获取对象

table SPEC (
  Special_Name varchar2 pk
  Signal integer
  Created_At date)

namespace App
{
    public class Strategy
    {
        public virtual string Id { get; private set; }
        public virtual int Signal { get; set; }
        public virtual DateTime CreatedAt { get; set; }
    }

    public class StrategyMap : ClassMap<Strategy>
    {
        public StrategyMap()
        {
            this.Table("SPEC");
            this.Id(x => x.Id).Column("Special_Name");
            Map(x => x.Signal).Column("Signal");
            Map(x => x.CreatedAt).Column("Created_At");
        }
    }
}

namespace App.Tests
{
    public class StrategyMapTest
    {
        private ISessionFactory sessionFactory;

        public StrategyMapTest()
        {
            this.sessionFactory = this.CreateSessionFactory();
        }

        [Fact]
        public void Can_read_from_database()
        {
            using (var session = this.sessionFactory.OpenSession())
            {
                var fromDb = session.Get<Strategy>("Foo 1");
                Assert.Equal("Foo 1", fromDb.Id);
                Assert.Equal("1", fromDb.Signal);
                Assert.Equal(new DateTime(2011,1,1), fromDb.CreatedAt);
            }
        }

        private ISessionFactory CreateSessionFactory()
        {
            return Fluently.Configure()
                .Database(OracleClientConfiguration
                    .Oracle10
                    .ConnectionString("connString"))
                .Mappings(m => m.FluentMappings
                    .AddFromAssemblyOf<Strategy>()
                    .ExportTo(@"C:\logs"))
                .BuildSessionFactory();
        }
    }
}

我在第一个断言中得到一个例外。没有从数据库中检索对象 - 它存在。

System.NullReferenceException: Object reference not set to an instance of an object.

我导出的映射看起来像这样

<hibernate-mapping xmlns="urn:nhibernate-mapping-2.2">
  <class xmlns="urn:nhibernate-mapping-2.2" name="App.Strategy, App, Version=1.0.0.0, Culture=neutral, PublicKeyToken=0af8b89e104ed570" table="SPEC">
    <id access="backfield" name="Id" type="System.String, mscorlib, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089">
      <column name="Special_Name" />
      <generator class="assigned" />
    </id>
    <property name="Signal" type="System.Int32, mscorlib, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089">
      <column name="Signal" />
    </property>
    <property name="CreatedAt" type="System.DateTime, mscorlib, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089">
      <column name="Created_At" />
    </property>
  </class>
</hibernate-mapping>

1 个答案:

答案 0 :(得分:1)

您是否检查过是否有任何SQL查询发送到数据库?您可以通过在数据库中使用分析器或最佳方法来查看,使用Nhibernate Profiler(商业但有免费试用)

如果没有发送SQL,那么您的配置存在一些问题(乍一看似乎没问题) 如果你看到发送了一个SQL查询,你可能会通过查看它来了解你的问题