如何在使用实体框架时获取所有用户角色
我在我的 ASP.NET 应用程序中使用实体框架和成员资格。
在其中一个页面中,我需要通过连接“aspnet_Membership”、“aspnet_Users”、“aspnet_Roles”和“aspnet_UsersInRoles”表来显示所有用户和角色。
但每当我尝试在 .edmx 中添加所有这些表时,“aspnet_UsersInRoles”实体不会被创建,而是“aspnet_Users”和“aspnet_Roles”与多对多关联相关联。我无法引用“aspnet_UsersInRoles”表,它会引发编译错误。
请帮助我获取用户角色,这是我的链接查询
var users = (from membership in IAutoEntity.aspnet_Membership
from user in IAutoEntity.aspnet_Users
from role in IAutoEntity.aspnet_Roles
where membership.IsApproved == true & membership.UserId == user.UserId
select new { user.UserName, membership.Email, user.aspnet_Roles.TargetRoleName, membership.CreateDate, user.LastActivityDate, membership.IsApproved }).ToList();
I am using entity framework and membership in my asp.net application.
In one of the pages I need to show all the users and ther roles by joing "aspnet_Membership", "aspnet_Users", "aspnet_Roles" and "aspnet_UsersInRoles" tables.
But whenever i try to add all these tables in the .edmx the "aspnet_UsersInRoles" entity is not getting created instead the "aspnet_Users" and "aspnet_Roles" are getting associated with a Many to Many association. And i can't refrence the "aspnet_UsersInRoles" table, its throwing an compilation error.
Please help me to get the user roles, this is my link query
var users = (from membership in IAutoEntity.aspnet_Membership
from user in IAutoEntity.aspnet_Users
from role in IAutoEntity.aspnet_Roles
where membership.IsApproved == true & membership.UserId == user.UserId
select new { user.UserName, membership.Email, user.aspnet_Roles.TargetRoleName, membership.CreateDate, user.LastActivityDate, membership.IsApproved }).ToList();
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
假设 EF 正在对用户类中名为
aspnet_Roles
的导航属性进行多对多关联建模,则您的 linq 查询几乎是正确的。唯一的问题是user.aspnet_Roles.TargetRoleName
您尝试在选择中为每个用户包含许多值(用于角色名称)。请记住,每个用户有多个角色。因此,您可以尝试选择为
注意,您将获得每个用户的角色集合,即
users[0].aspnet_roles
将是该集合。如果保证始终有一个角色与用户关联,那么您可以使用以下语法:
注意,我们正在从与用户关联的角色中选择第一个角色的名称。如果用户没有角色,则
First()
方法将抛出异常。此外,我不确定从应用程序逻辑的角度来看,仅选择第一个角色的名称是否就足够了。Assuming that EF is modelling many-to-many association with navigation property called
aspnet_Roles
in the user class, your linq query is almost correct. Only issue isuser.aspnet_Roles.TargetRoleName
where you had tried to include many values (for role names) per user in your select.Remember that you have many roles per user. So you can try out select as
Note that you will get the roles collection for each user i.e.
users[0].aspnet_roles
will be the collection.If there is guarantee that there will always one role associated with the user then you can use syntax such as
Note that we are selecting the name of first role from roles associated with the user. If there is no role for the user then
First()
method will throw an exception. Besides, I am not certain if selecting only first role's name would suffice from application logic perspective.