使用ApplicationUser从另一个表获取值始终为null

时间:2018-07-17 10:04:00

标签: c# asp.net-mvc entity-framework

我正在尝试使用“应用程序用户”访问Docente表,但是“ user.Docente”的返回值始终为null

ApplicationUser.cs

public class ApplicationUser : IdentityUser
{
    public virtual Docente Docente { get; set; }
}

Docente.cs

public class Docente
{
    public int DocenteId { get; set; }
    public string Nome { get; set; }
    public string Imagem { get; set; }
    public int DepartamentoId { get; set; }
    public string UserId { get; set; }

    public virtual ApplicationUser ApplicationUser { get; set; }
}

AccountController.cs

    [HttpPost]
    [AllowAnonymous]
    [ValidateAntiForgeryToken]
    public async Task<IActionResult> Login(LoginViewModel model, string returnUrl = null)
    {
        ViewData["ReturnUrl"] = returnUrl;


        ApplicationUser user = null;
        user = _context.ApplicationUser.Single(u => u.Email.Equals(model.Email));


        var getuserId = user.Docente.DepartamentoId;

1 个答案:

答案 0 :(得分:2)

我不确定您的延迟加载是否由于某种原因而关闭,因此我建议您尝试手动添加Docente导航属性:

user = _context.ApplicationUser
               .Include(u => u.Docente) // this requires System.Data.Entity namespace
               .Single(u => u.Email.Equals(model.Email));