SolvedPrivate

How can I do this SQL in LINQ?

Posted on 2014-11-23
10
47 Views
Last Modified: 2016-02-16
This is MVC Identity. Please see attached screenshot.

If this is too complicated, I'll just do this in a stored proc.

I want to get a list of users and their roles. The table structure has changed with MVC Identity. I know I can get the users and roles like this but I want to join them together

var context = new ApplicationDbContext();
var allUsers = context.Users.ToList();
var allRoles = context.Roles.ToList();

Open in new window


I tried joining them together but looks like I need to drill down to RoleId somehow.

This is what I want

select u.Id,
       u.Email,
	   U.username,
	   r.Name,
	   ur.userId,
	   ur. RoleId

	   from [dbo].[AspNetUsers] u
	   left join [dbo].[AspNetUserRoles] ur on ur.userId = u.Id
	   left join [dbo].[AspNetRoles] r on r.id =ur.RoleId

Open in new window


I tried this but this brings back 4 rows. It should be 2. I think the left join is wrong.
 var users = (from r in roles
                        join u in allusers on r.Users.Select(m => m.UserId).ToString() equals u.Roles.Select(m =>m.UserId).ToString()
                         select new
                         {
                             u.Id,
                             u.UserName,
                             u.Email,
                               r.Name,
                              RoleId = r.Id

                         }).ToList();

Open in new window

Identity.png
0
Comment
Question by:Camillia
  • 7
  • 3
10 Comments
 
LVL 18

Expert Comment

by:Richard Lee
Comment Utility
Hey Camilla,

You can try something like below:

var context = new ApplicationDbContext();
                                
var query = 
    from u in context.Users
        join ur in context.UserRoles on u equals ur.UserId = u.Id
        join r in context.Roles on r equals r.Id = ur.RoleId
    select new {
        Users = u, Roles = r
    }

Open in new window


Hope this helps!
0
 
LVL 7

Author Comment

by:Camillia
Comment Utility
Thanks, Richard! I thought no one would respond. Was about to do it in a stored proc. Let me try it and will post back right away.
0
 
LVL 7

Author Comment

by:Camillia
Comment Utility
No, there's no UserRoles table. Even tho you see it in the screenshot (SQL)...in MVC Identity...it seems like I have to drill down in the "Role" to get do a join.

See attached screenshot. My LINQ above works but it's the left join that I'm missing because there might not be roles so I have to do a left join.
roles.png
0
 
LVL 7

Author Comment

by:Camillia
Comment Utility
Tried this as well but still get 4 rows. See attached screeshot. I think this is because I have 2 roles. I must be missing another join.

  var test = (from r in roles
                         join u in allusers on r.Users.Select(m => m.UserId).ToString() equals u.Roles.Select(m => m.UserId).ToString()
                         into JoinedEmpDept
                        from u in JoinedEmpDept.DefaultIfEmpty()
                         select new
                         {
                             u.Id,
                             u.UserName,
                             u.Email,
                             r.Name,
                             RoleId = r.Id

                         }).ToList();

Open in new window

roles2.png
0
 
LVL 18

Accepted Solution

by:
Richard Lee earned 500 total points
Comment Utility
Have you tried this approach.

var userManager = HttpContext.Current.GetOwinContext().GetUserManager<ApplicationUserManager>();
var rolesForUser = userManager.GetRoles(user.Id);

Open in new window


http://typecastexception.com/post/2014/06/22/ASPNET-Identity-20-Customizing-Users-and-Roles.aspx#A-Note-About-IdentityRole-and-IdentityUserRole
0
Enabling OSINT in Activity Based Intelligence

Activity based intelligence (ABI) requires access to all available sources of data. Recorded Future allows analysts to observe structured data on the open, deep, and dark web.

 
LVL 18

Expert Comment

by:Richard Lee
Comment Utility
Here is another solution. It seems like out of the box the AccountController has methods to get the roles for a user.

var account = new AccountController();
var userRoles = account.UserManager.GetRoles(user.Id);

Open in new window


Hope this helps!
0
 
LVL 7

Author Comment

by:Camillia
Comment Utility
oh, let me take a look
0
 
LVL 7

Author Comment

by:Camillia
Comment Utility
Can it be joined to context.Users to get a list of users and their corresponding roles? like that what I was trying to do above? if not, looks like a stored proc is easier
0
 
LVL 7

Author Comment

by:Camillia
Comment Utility
The solution in ID: 40462216  gives me the role for one user. That's good.
I still wonder if I can get a list of users with their roles. I Googled a lot last night but not much came up.
0
 
LVL 7

Author Closing Comment

by:Camillia
Comment Utility
I'll open another question. You've answered this one. Thanks
0

Featured Post

How your wiki can always stay up-to-date

Quip doubles as a “living” wiki and a project management tool that evolves with your organization. As you finish projects in Quip, the work remains, easily accessible to all team members, new and old.
- Increase transparency
- Onboard new hires faster
- Access from mobile/offline

Join & Write a Comment

Problem Hi all,    While many today have fast Internet connection, there are many still who do not, or are connecting through devices with a slower connect, so light web pages and fast load times are still popular.    If your ASP.NET page …
More often than not, we developers are confronted with a need: a need to make some kind of magic happen via code. Whether it is for a client, for the boss, or for our own personal projects, the need must be satisfied. Most of the time, the Framework…
Illustrator's Shape Builder tool will let you combine shapes visually and interactively. This video shows the Mac version, but the tool works the same way in Windows. To follow along with this video, you can draw your own shapes or download the file…
This video shows how to remove a single email address from the Outlook 2010 Auto Suggestion memory. NOTE: For Outlook 2016 and 2013 perform the exact same steps. Open a new email: Click the New email button in Outlook. Start typing the address: …

762 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question

Need Help in Real-Time?

Connect with top rated Experts

9 Experts available now in Live!

Get 1:1 Help Now