NHibernate 3.2 Linq与相关子查询

时间:2011-06-02 21:44:27

标签: linq nhibernate

任何人都可以帮助尝试在Linq中对NHibernate 3.2执行以下SQL吗?

select act.Name from Activity act
where 1 = 
(
  select top 1 p.Allow
  from Permissions p inner join Operations o on p.OperationId = o.OperationId
  inner join Users u on p.UserId = u.UserId
  where p.EntitySecurityKey = act.ActivityId and o.Name = '/operation'
  and u.Name = 'user'
  order by p.Level desc, p.Allow asc
)

这在SQL中运行得非常好但我无法理解如何使用Linq来完成等效操作。

1 个答案:

答案 0 :(得分:0)

此处不需要相关的子查询。在EntitySecurityKey.Name时,您的所有外部查询都会获取Allow == true。您可以在查询后使用简单的if语句执行该逻辑。

private string GetEntitySecurityKeyNameIfAllowed(ISession session, string operationName, string userName)
{
    var result = session.Query<Permission>()
        .Where(p => p.Operation.Name == operationName
            && p.User.Name == userName)
        .OrderByDescending(p => p.Level)
        .ThenBy(p => p.Allow)
        .Select(p => new
        {
            p.Allow,
            p.EntitySecurityKey.Name
        })
        .FirstOrDefault();

    return result != null && result.Allow
        ? result.Name
        : null;
}
相关问题