我需要能够分配可能处于多个角色的用户...... [英] I need to be able to assign a users who may be in multiple roles...

查看:65
本文介绍了我需要能够分配可能处于多个角色的用户......的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

目前我有以下代码片段...我希望能够列出可能担任不同角色的用户...而不仅仅是学生角色。是否有一般关键字或我可以使用的东西而不是角色名称?



这是我的代码:



Currently I have the piece of code below... I want to be able to list users who may be in different roles... not just a student role. Is there a general keyword or something I could use instead of the role name?

Here is my code:

<            //get user role id
            var roleId = db.Roles.SingleOrDefault(r => r.Name == "Student").Id;
            //get all users assigned to company
            var users = db.Company.Find(companyId).Users;
            //restrict list to developers only
            var devs = users.Where(user => user.Roles.Any(role => role.RoleId == roleId));
            //return the list of devs
            return devs.ToList();





我尝试过:



我试过把学生的字符串留空...尝试用#替换它。



What I have tried:

I have tried leaving the string with "Student" empty... tried replacing it with "#".

推荐答案

对于不同角色的用户,您需要获取所有这些角色的 roleId ,然后在其他查询中使用该角色。



如果您可以更改架构,更好的方法可能是将 user.Roles 更改为外键引用角色表。我认为这一切都可以用连接重写为单个查询。 (我不是SQL saavy足以在没有更多信息的情况下尝试它。)



另外,你的 roleId 如果找不到与给定名称匹配的任何角色,> query将抛出 NullReferenceException 。 (在这种情况下, SingleOrDefault 将返回 null .Id 将抛出异常!)您应该在解除引用之前检查 null 以获取 Id 。如果有多个匹配,它也会抛出异常。
For the users in "different roles", you need to get the roleId of all of those roles and then use that in the other query.

If you can change the schema, an even better way might be to change the user.Roles to be foreign key references to the Roles table. I think then this all could be rewritten as a single query with joins. (I'm not SQL saavy enough to attempt it without a bunch more info.)

Also, your roleId query will throw a NullReferenceException if it doesn't find any roles matching the given name. (The SingleOrDefault will return null in that case and the .Id will throw the exception!) You should check for the null before dereferencing to get the Id. It will also throw an exception if there is more than one match.


这篇关于我需要能够分配可能处于多个角色的用户......的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆