2014-11-04 48 views
0

我想编写一个DAO方法来检查一个组的所有用户是否有特定的用户角色并返回false或true。如何使用linq to sql检查组的所有用户都具有用户角色?

我使用NHibernate ad LINQ。

这是我迄今所做的:

public bool AllByGroupHaveUserRole(Group group, UserRole userRole) 
{ 
    if (group == null) 
    { 
     throw new ArgumentNullException("group"); 
    } 

    if (userRole == null) 
    { 
     throw new ArgumentNullException("userRole"); 
    } 

    var groups = HibernateTemplate.Execute(session => (from user in session.Query<User>() 
                 where user.Group == @group 
                 group user by user.UserRole.Id into groupedUsers 
                 select new { groupedUsers.Key })).ToList(); 

    return groups.Count < 2 && groups.All(o => o.Key == userRole.Id); 
} 

现在,我执行查询的数据库,后来我在内存检查的UserRole的。

是否有可能在一个NHibernate查询中做到这一切,只是返回结果?

如果在具有特定用户角色的组中没有用户,则该方法也应该返回true。

这也是LINQ方法IEnumerable.All方法的工作原理。

Return Value: True if every element of the source sequence passes the test in the specified predicate, or if the sequence is empty; otherwise, False. 
+0

是否有任何人谁可以帮我吗? – 2014-11-05 08:05:23

回答

0

余did't测试代码

from user in session.Query<User>() 
         where user.Group == @group 
         group user by new { RoleId = user.UserRole.Id } into groupedUsers 
         select groupedUsers.Select(t => t.UserRole.Id).Distinct().Count() < 2 || groupedUsers.Where(t => t.UserRole == userRole).Any() 
+0

它的工作!谢谢。 – 2014-12-07 13:26:06

相关问题