Reputation: 53
I have added DepartmentId column as Foreign Key in AspNetUsers table and also i have the same DepartmentId as ForeignKey in another table called MaterialRequest i want login user's Department Name to be displayed in the View As 'Department Name'
My Classes
Department
DepartmentId DepartmentName
MaterialRequest
MaterialRequestId MaterialName DepartmentId
What i have tried
public ActionResult Index(int? id)
{
var user = User.Identity.GetUserId();
ViewBag.DeptName=db.Query<AspNetUser>("Select DepartmentId from AspNetUsers where Id = '@0'",id);
}
Upvotes: 0
Views: 1146
Reputation: 3228
There is a way around this, you can create a claim and get this way:
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; }
}
Then create an extension method to get your 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;
}
}
}
And now you can easily call this method to get your DepartmentId:
var departmentId= User.Identity.GetDepartmentId();
Upvotes: 1