[英]How to fetch data from database table which is connected to AspNetUsers table in mvc 5
我已经在AspNetUsers表中将 DepartmentId列添加为外键,并且在另一个表中也具有与ForeignKey相同的DepartmentId称为MaterialRequest,我希望登录用户的部门名称在“部门名称”视图中显示
我的课程
部
DepartmentId DepartmentName
MaterialRequest
MaterialRequestId MaterialName部门编号
我尝试过的
public ActionResult Index(int? id)
{
var user = User.Identity.GetUserId();
ViewBag.DeptName=db.Query<AspNetUser>("Select DepartmentId from AspNetUsers where Id = '@0'",id);
}
有一种解决方法,您可以创建索赔并获得以下方式:
public class ApplicationUser : IdentityUser
{
public async Task<ClaimsIdentity> GenerateUserIdentityAsync(UserManager<ApplicationUser> manager)
{
// Note the authenticationType must match the one defined in CookieAuthenticationOptions.AuthenticationType
var userIdentity = await manager.CreateIdentityAsync(this, DefaultAuthenticationTypes.ApplicationCookie);
// Add custom user claims here
// Add custom user claims here => this.DepartmentId is a value stored in database against the user
userIdentity.AddClaim(new Claim("DepartmentId", this.DepartmentId.ToString()));
return userIdentity;
}
// Your Extended Properties
public int? DepartmentId { get; set; }
}
然后创建一个扩展方法来获取您的departmentId:
namespace App.Extensions
{
public static class IdentityExtensions
{
public static string GetDepartmentId(this IIdentity identity)
{
var claim = ((ClaimsIdentity)identity).FindFirst("DepartmentId");
// Test for null to avoid issues during local testing
return (claim != null) ? claim.Value : string.Empty;
}
}
}
现在,您可以轻松地调用此方法来获取DepartmentId:
var departmentId= User.Identity.GetDepartmentId();
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.