Как получить данные из таблицы базы данных, которая подключена к таблице AspNetUsers в mvc 5 - PullRequest
0 голосов
/ 15 декабря 2018

Я добавил столбец DepartmentId в качестве внешнего ключа в таблицу AspNetUsers , а также у меня такой же DepartmentId , как ForeignKey, в другой таблице с именем MaterialRequest я хочу, чтобы имя отдела регистрации пользователя отображалось в представлении «Имя отдела»

Мои классы

Отдел

DepartmentId DepartmentName

MaterialRequest

MaterialRequestId MaterialName DepartmentId

Что я пробовал

        public ActionResult Index(int? id)
        {
  var user = User.Identity.GetUserId();
            ViewBag.DeptName=db.Query<AspNetUser>("Select DepartmentId from AspNetUsers where Id = '@0'",id);
}

1 Ответ

0 голосов
/ 15 декабря 2018

Существует способ обойти это, вы можете создать заявку и получить этот способ:

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();
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...