我需要能够分配可能处于多个角色的用户...... [英] I need to be able to assign a users who may be in multiple roles...
本文介绍了我需要能够分配可能处于多个角色的用户......的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
目前我有以下代码片段...我希望能够列出可能担任不同角色的用户...而不仅仅是学生角色。是否有一般关键字或我可以使用的东西而不是角色名称?
这是我的代码:
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 theroleId
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 theuser.Roles
to be foreign key references to theRoles
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, yourroleId
query will throw aNullReferenceException
if it doesn't find any roles matching the given name. (TheSingleOrDefault
will returnnull
in that case and the.Id
will throw the exception!) You should check for thenull
before dereferencing to get theId
. It will also throw an exception if there is more than one match.
这篇关于我需要能够分配可能处于多个角色的用户......的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文