【问题标题】:asp.net 5 custom IdentityUser properties are nullasp.net 5 自定义 IdentityUser 属性为空
【发布时间】:2015-12-29 02:41:08
【问题描述】:

我有这门课:

public class AppUser : IdentityUser
{
  public virtual Organization Organization { get; set; }
}

当我在控制器操作中获取用户时:

public async Task<IActionResult> MyAction()
{
  var user = await GetCurrentUserAsync();
  if (user != null)
  {
    // **user.Organization is null here**
  }
  return View();
}

...

private async Task<AppUser> GetCurrentUserAsync()
{
  return await _userManager.FindByIdAsync(HttpContext.User.GetUserId());
}

我可以获取所有用户属性,但不能获取我添加的自定义属性。我检查了数据库,并在 aspnetusers db 中为此用户设置了“组织”。

有什么想法吗?

【问题讨论】:

标签: asp.net-core-mvc entity-framework-core


【解决方案1】:

标识框架 3 似乎不支持延迟加载。除非您编写自己的 FindByIdAsync 方法来急切加载所需的依赖表,否则急切加载似乎也不是一种选择。

将 OrganizationId 添加为属性可能更容易

public class AppUser : IdentityUser
{
    public int OrganizationId { get; set; }
    public  Organization Organization { get; set; }
}

您将需要创建迁移并在更改后更新您的数据库

这将允许您在不做任何额外工作的情况下引用组织 ID,例如

var orgId = user.OrganizationId;

如果您想获取组织的其他非主键属性,您必须创建自己的 Identity Framework 3 FindByIdAsync 方法,或者只创建一个单独的数据库查询。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2014-05-17
    • 1970-01-01
    • 1970-01-01
    • 2017-03-24
    • 2014-10-25
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多