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 "aspn开发者_StackOverflow社区et_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();
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 is user.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
select new { user.UserName, membership.Email, user.aspnet_Roles, membership.CreateDate ...
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
select new { user.UserName, membership.Email, user.aspnet_Roles.First().TargetRoleName, membership.CreateDate ...
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.
精彩评论