2011-06-02 100 views
3

任何人都可以帮助尝试在Linq中执行以下SQL到NHibernate 3.2?NHibernate 3.2 Linq与相关的子查询

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做等效。

+0

你有没有这方面的运气?我试图做几乎相同的事情。我有Linq语句算出来,并与LinqPad工作,但我不能让NHibernate执行它。请参阅http://stackoverflow.com/questions/15206860/nhibernate-subquery-in-where-with-linq – Ragesh 2013-03-04 17:01:12

回答

0

这里不需要相关的子查询。当Allow == true时,您的所有外部查询都会执行EntitySecurityKey.Name。您可以在查询后用简单的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; 
}