2013-10-24 34 views
1

我有一個使用nHibernate的小型POC應用程序。這是我第一次自己設置nHibernate,但之前我曾使用它。出於某種原因,我的查詢沒有返回任何數據。我可以確認我的數據庫中有一個Product流利的nHibernate不返回數據

public class NHibernateHelper 
{ 
    private static String _connectionString = 
     @"Server=localhost\SQLEXPRESS;Database=TestProject;User ID=TestProjectMvc;Password=Pa$$word"; 

    private static ISessionFactory _sessionFactory; 

    private static ISessionFactory SessionFactory 
    { 
     get 
     { 
      if (_sessionFactory == null) 
       InitializeSessionFactory(); 

      return _sessionFactory; 
     } 
    } 

    private static void InitializeSessionFactory() 
    { 
     _sessionFactory = Fluently.Configure() 
      .Database(MsSqlConfiguration.MsSql2008.ConnectionString(_connectionString).ShowSql() 
      ).Mappings(m => m.FluentMappings.AddFromAssemblyOf<Product>()) 
      //.ExposeConfiguration(cfg => new SchemaExport(cfg).Create(true, true)) 
      .BuildSessionFactory(); 
    } 

    public static ISession OpenSession() 
    { 
     return SessionFactory.OpenSession(); 
    } 
} 

我的映射類:

public class ProductMap : ClassMap<Product> 
{ 
    public ProductMap() 
    { 
     Id(x => x.Id); 
     Map(x => x.Name); 
     References(x => x.Category).Column("CategoryId"); 
    } 
} 

,我使用檢索數據的方法:

public IEnumerable<Product> GetAllProducts() 
    { 
     using (var session = NHibernateHelper.OpenSession()) 
     { 
      var list = session.QueryOver<Product>().List(); 
      return list; 
     } 
    } 
+1

您的映射和域對象在同一個程序集? –

+0

@SimonWhitehead Ahh就是這樣......我改變了我的'Mappings'從'ProductMap'程序集加載,現在我看到了數據。謝謝!如果你想,發佈你的答案,我會標記爲這樣。 – gwin003

回答

3

從另一種類型的裝配總是加入映射難以置信的有益的方法絆倒其他人。

爲別人想..這個問題是這樣的:

.AddFromAssemblyOf<Product>() 

ProductProductMap是在不同的組件。因此,在Product駐留的程序集中找不到映射。

我已經看到這次旅行開始了很多人!

+1

很好的解釋!哈哈大多數人不會付出這麼多努力來寫一個他們已經知道的答案會被標記爲答案。獎勵! – gwin003

0

另外 - 如果您使用SchemaExport爲您生成數據庫表 -/do /記得在第二次運行該應用程序時關閉它。否則,它是空白表再次爲你...