asp.net 5 个自定义 IdentityUser 属性为空
asp.net 5 custom IdentityUser properties are null
我有这个class:
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 数据库中为此用户设置了 'Organization'。
有什么想法吗?
身份框架 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
方法或创建一个单独的数据库查询。
我有这个class:
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 数据库中为此用户设置了 'Organization'。
有什么想法吗?
身份框架 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
方法或创建一个单独的数据库查询。