2010-08-27 69 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; 
} 

第三,潜在的问题可能是因为您对您的表名双引号。这表明映射问题。表名不匹配或类似的东西。