NHibernate QueryOver 与多对多

NHibernate QueryOver with Many-to-Many

我正在学习 QueryOver,但我不知道如何进行简单的多对多查询。

我有三个表,Users、Roles 和一个联结 UserRoles。

Users       UserRoles         Roles
=======     =============     =========
UserId      UserId            RoleId
Username    RoleId            Role
Firstname   Date

我的表是这样连接的:

Users.UserId -> UserRoles.UserId
Roles.RoleId -> UserRoles.RoleId 

我正在尝试 select 使用 QueryOver 的特定用户名的角色基本上是以下替代方法:

SELECT 
    dbo.Roles.Role 
FROM dbo.Roles 
INNER JOIN dbo.UserRoles 
    ON dbo.Roles.RoleId = dbo.UserRoles.RoleId 
INNER JOIN dbo.Users 
    ON dbo.UserRoles.UserId = dbo.Users.UserId 
WHERE (Username = @Username)

类:

public class Roles
{
    public virtual int RoleId { get; set; }
    public virtual string Role { get; set; }
}
public class UserRoles
{
    public virtual int UserId { get; set; }
    public virtual int RoleId { get; set; }
    public virtual DateTime Date { get; set; }
}
public class Users
{
    public virtual int UserId { get; set; }
    public virtual string Username { get; set; }
    public virtual string FirstName { get; set; }
    public virtual string LastName { get; set; }
    public virtual string Email { get; set; }
    public virtual DateTime Date { get; set; }
}

映射:

<class name="Roles">
<id name="RoleId">
  <generator class="native" />
</id>
<property name="Role" />
</class>

<class name="UserRoles">
<property name="UserId" />
<property name="RoleId" />
<property name="Date" />
</class>

<class name="Users">
<id name="UserId">
<generator class="native" />
</id>
<property name="Username" />
<property name="FirstName" />
<property name="LastName" />
<property name="Email" />
<property name="Date" />
</class>

我已经尝试了一些,但我什至不接近:

var result = session.QueryOver<Users>()
            .Right.JoinQueryOver<Roles>(x => x.UserId )
            .Where(c => c.RoleId == roleid)
            .List();

这个连接实际上应该有效。我认为您需要用户而不是角色。所以你可能想使用类似的东西:

var result = session.QueryOver<Users>()
            .Right.JoinQueryOver<Roles>(x => x.UserId )
            .Where(c => c.RoleId == roleid)
.TransformUsing(Transformers.DistinctRootEntity)
.List();

根据我对 NHibernate 的理解,您当前拥有的映射不允许您进行适当的查询,但是如果您可以将至少 UserRoles 实体更改为,

    public class UserRoles
    {
        public virtual int Id { get; set; }
        public virtual Users Users { get; set; }
        public virtual Roles Roles { get; set; }
    }

然后你可以使用下面的方法来实现你想要的,

    Users users = null;
    UserRoles userRoles = null;


    var query = session.QueryOver(() => userRoles)
        .JoinQueryOver(() => userRoles.Users, () => users)
        .Where(() => users.Username == "test")
        .Select(r => r.Roles)
        .TransformUsing(Transformers.DistinctRootEntity);

    var results = query.List();