ASP.NET如何访问AspNetUsers表并返回值

时间:2017-04-29 04:19:04

标签: asp.net asp.net-web-api

我成功地在AspNetUsers表中添加了一些字段,但我不知道如何检索它们。我的项目是asp.net web api,我可以从令牌中检索用户名。我想通过给定的userId或用户名返回departmentId。 并尝试,但这给了我无效的

   private ApplicationUserManager _userManager;


        public int GetdeptId(string username)
        {
           var dept =  _userManager.Users.Where(d => d.UserName == username).Select(c => c.DepartmentId).FirstOrDefault();
            return dept;


        }

这是我在AspNetUsers中创建字段的方法,我可以成功插入值。问题是从AspNetUsers返回值。

public class RegisterBindingModel
    {
        [Required]
        [Display(Name = "Email")]
        public string Email { get; set; }

        [Required]
        [Display(Name = "FirstName")]
        public string FirstName { get; set; }

        [Required]
        [Display(Name = "Lastname")]
        public string Lastname { get; set; }

        [Required]
        [Display(Name = "Department")]
        public int DepartmentId { get; set; }



        [Required]
        [StringLength(100, ErrorMessage = "The {0} must be at least {2} characters long.", MinimumLength = 6)]
        [DataType(DataType.Password)]
        [Display(Name = "Password")]
        public string Password { get; set; }

        [DataType(DataType.Password)]
        [Display(Name = "Confirm password")]
        [Compare("Password", ErrorMessage = "The password and confirmation password do not match.")]
        public string ConfirmPassword { get; set; }
    }

然后注册

public async Task<IHttpActionResult> Register(RegisterBindingModel model)
        {
            if (!ModelState.IsValid)
            {
                return BadRequest(ModelState);
            }

            var user = new ApplicationUser() { UserName = model.Email, Email = model.Email, Firstname = model.FirstName, LastName =        model.Lastname, DepartmentId = model.DepartmentId };

            IdentityResult result = await UserManager.CreateAsync(user, model.Password);

            if (!result.Succeeded)
            {
                return GetErrorResult(result);
            }

            return Ok();
        } 

提前谢谢!

2 个答案:

答案 0 :(得分:0)

尝试!

var context = new IdentityDbContext();

var users = context.Users.ToList();

答案 1 :(得分:0)

如果您可以访问Application_bContext,例如_db,则可以将其强制转换为IdentityDbContext并通过该表访问表。例如 IdentityDbContext context = _db as IdentityDbContext; IEnumerable<User> users = context.Users;