2010-08-27 67 views
1

好吧,我有一個類,Company我想不出什麼我做錯了這個基本NHibernate的查詢

public class Company 
{ 
    public virtual int Id { get; set; } 
    public virtual IList<Role> Roles { get; set; } 
} 

而另一個類,Role

public class Role 
{ 
    public virtual int Id { get; set; } 
    public virtual Company Company { get; set; } 
    public virtual RoleLevel RoleLevel { get; set; } 
} 

我使用流利的自動映射,沒有什麼特別的。

我有這樣的方法:

private RoleLevel GetRole(int companyId) 
{ 
    var allRoles = Session.CreateCriteria<Role>().List<Role>(); 

    var role = Session.CreateCriteria<Role>() 
     .CreateAlias(NameOf<Role>.Property(r => r.Company), "c") 
     .Add(Restrictions.Eq("c.Id", companyId)) 
     .UniqueResult<Role>(); 

    return (role == null) ? RoleLevel.Restricted : role.RoleLevel; 
} 

companyId被傳遞作爲102。如果我檢查allRoles陣列,其中一個涉及公司#102。但是應該返回單個的查詢返回null

我在做什麼錯?

EDIT 1

通過請求,這裏是正在執行的查詢,根據NHProf:

SELECT this_.Id   as Id75_1_, 
     this_.Version as Version75_1_, 
     this_.RoleLevel as RoleLevel75_1_, 
     this_.DbDate  as DbDate75_1_, 
     this_.Account_id as Account5_75_1_, 
     this_.Company_id as Company6_75_1_, 
     c1_.Id   as Id71_0_, 
     c1_.Version  as Version71_0_, 
     c1_.Name   as Name71_0_, 
     c1_.OnyxAlias as OnyxAlias71_0_, 
     c1_.DbDate  as DbDate71_0_, 
     c1_.Parent_Id as Parent6_71_0_ 
FROM "Role" this_ 
     inner join "Company" c1_ 
     on this_.Company_id = c1_.Id 
WHERE c1_.Id = 102 /* @p0 */ 

編輯2

我試圖改變數據庫到SQL Server。在SQL Server中,它一切正常。我想這是NHibernate如何連接到SQLite數據庫的錯誤?現在,我可以使用SQL Server數據庫進行測試,但爲了速度的原因,我希望將來可以使用In Memory SQLite數據庫。

+1

你使用SQL Server嗎?如果是,請嘗試在服務器上運行跟蹤並查看該查詢。它可能會幫助你檢測你是否做錯了什麼。 – devnull 2010-08-27 14:43:41

+0

這是一個測試,所以它使用SQLite。我將添加正在執行的查詢到我的問題。 – 2010-08-27 14:47:57

+1

NHProf應該在底部有一個選項 - 「查看由此查詢產生的n行」。有沒有結果? (您必須在NHProf中配置連接才能使用此功能。) – Jay 2010-08-27 15:33:18

回答

1

首先你要對數據庫運行查詢嗎?

其次,如果映射有問題,您可以嘗試使用另一個CreateCriteria嗎?然後你可以像下面那樣確定聯合類型。只是爲了確保我們已經嘗試了所有的基礎之前,我們繼續移動:)

private RoleLevel GetRole(int companyId) 
{ 
    var allRoles = Session.CreateCriteria<Role>().List<Role>(); 

    var role = Session.CreateCriteria<Role>("r") 
     .CreateCriteria("Company", "c", JoinType.LeftOuterJoin) 
     .Add(Restrictions.Eq("c.Id", companyId)) 
     .UniqueResult<Role>(); 

    return (role == null) ? RoleLevel.Restricted : role.RoleLevel; 
} 

第三,潛在的問題可能是因爲您對您的表名雙引號。這表明映射問題。表名不匹配或類似的東西。