循环实体引用是正确的方法吗?
我想让所有对用户名列表具有特定角色的用户。
正在使用 .Ininclude 包含所有用户,并遍历 UsersReference 循环遍历与该角色关联的所有用户的最佳方法?
我注意到我无法执行 foreach(User user in role.Users) 但 UsersReference 似乎可以工作,但这是应该如何完成的?浏览参考文献?
using (var context = new MyEntities())
{
List<string> users = new List<string>();
Role role = (from r in context.Roles.Include("Users")
where r.RoleName == roleName
select r).FirstOrDefault();
foreach (User user in role.UsersReference)
users.Add(user.UserName);
return users.ToArray();
}
I want to get all users that have a specific role to a list of usernames.
Is using .Include to include all the users, and going through the UsersReference
the best way to loop through all the users that are associated with the role?
I noticed I could not do a foreach(User user in role.Users) but UsersReference seem to work, but is that how it's supposed to be done? Going through the reference?
using (var context = new MyEntities())
{
List<string> users = new List<string>();
Role role = (from r in context.Roles.Include("Users")
where r.RoleName == roleName
select r).FirstOrDefault();
foreach (User user in role.UsersReference)
users.Add(user.UserName);
return users.ToArray();
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
您的 Role 表是否有可能具有 Users 属性?我认为它将命名导航属性 Users,而不是 UsersReference。我不使用 EF,但我见过的所有示例都在表之后命名属性。 AFAIK 它总是实现 IEnumerable 所以你应该能够在 foreach 中使用它。
如果你设置正确,我想你只需要:
Is it possible that your Role table has a Users property? I would think that it would name the navigation property Users, not UsersReference. I don't use EF, but all the examples I've seen name the property after the table. AFAIK it always implements IEnumerable so you should be able use it in a foreach.
If you have it set up right I think you only need:
尝试将原始 foreach 循环与 ToList()
foreach(var user in role.Users.ToList()) {...}
一起使用Try using your original foreach loop with ToList()
foreach(var user in role.Users.ToList()) {...}
请改用
.ToArray()
帮助程序。请注意,如果您这样做,则不需要
.Include("Users")
。在查询中使用r.Users
会使其出现在一个查询中,而无需包含它,因为它是在活动的 ObjectContext 中使用的。附带说明一下,我不确定此方法的方法签名是什么,但在这种情况下
IEnumerable
可能比string[]
更合适,因为您可以稍后调整实现,而无需从其他类型的集合创建数组。Use the
.ToArray()
helper insteadNote that there's no need for
.Include("Users")
if you do it this way. Usingr.Users
in the query causes it to be in one query without the need for including it, because it's used in an active ObjectContext.One a side note, I'm not sure what the method signature of this method is, but in this case
IEnumerable<string>
is probably a better fit thanstring[]
, because you can adjust the implementation later without creating arrays from other types of collections.