获取角色中的所有用户。 ASP.NET标识

时间:2016-03-29 09:24:13

标签: c# asp.net asp.net-identity asp.net-roles

我可以得到像这样的所有用户

var users = UserManager.Users.ToList();

我可以找到像这样的角色

var role = db.Roles.SingleOrDefault(m => m.Name == "User");

我想列出所有具有角色名称的用户"用户"在AspNetRoles表中(我有UserAdmin)。

var role = db.Roles.SingleOrDefault(m => m.Name == "User");
var usersInRole = db.Users.Where(m => m.Roles.Any(r => r.RoleId == role.Id)).ToList();

return View(usersInRole);

我在var role中获得了该角色,但在我调试时userInRole给了我Count = 0。没有编译错误。

4 个答案:

答案 0 :(得分:3)

您可以使用下面的代码来检索具有特定角色(Identity 2.x.x)的所有用户:

  <?php

 $con = mysqli_connect("localhost","root","") or die (mysql_error());

mysqli_select_db($con, 'studentform');

    if(isset($_POST['submit']))
    {
        $file = $_FILES['file']['tmp_name'];
        $handle = fopen($file,"r");
        while(($fileop = fgetcsv($handle,1000,",")) !==false)
        {

            $gender = $fileop[0];
            $track = $fileop[1];
            $last = $fileop[2];
            $first = $fileop[3];
            $sql= mysqli_query("INSERT INTO student (gender,track,last,first) VALUES ('$gender','$track','$last','$first')");
        }
        if($sql)
        {
            echo "data uploaded successfully";
        }
        else{
            echo "error";
        }
    }

?>

同步用法:

var users = await _userManager.GetUsersInRoleAsync("RoleName");

答案 1 :(得分:2)

var usersInRole = db.Users.Where(m => m.Roles.RoleId == role.Id)).ToList();

您搜索所有用户并返回符合特定角色ID的用户

答案 2 :(得分:0)

您是否尝试过使用导航属性Lazy Loading?

var role = db.Roles.SingleOrDefault(m => m.Name == "User");
var usersInRole = role.Users;

答案 3 :(得分:0)

您可以使用Linq表达式基本查询,如下所示:

public class AppData {
    static SharedPreferences prefdata;
    static SharedPreferences.Editor editordata;

    static final String  FCOLOR_KEY = "#FFFFFF"; //first color
    static final String SCOLOR_KEY = "#FFFFFF"; //second color
    static final String TCOLOR_KEY = "#FFFFFF"; //text color
    static final String ICOLOR_KEY = "#FFFFFF"; //icon color
    static final Image BIMG_KEY = null; //bakcground image

}