问题描述
我扩展了 IdentityUser
以包含用户地址的导航属性,但是当使用 UserManager.FindByEmailAsync
获取用户时,导航属性未填充.ASP.NET Identity Core 是否有某种方法来填充导航属性,例如 Entity Framework 的 Include()
,还是我必须手动完成?
I've extended IdentityUser
to include a navigation property for the user's address, however when getting the user with UserManager.FindByEmailAsync
, the navigation property isn't populated. Does ASP.NET Identity Core have some way to populate navigation properties like Entity Framework's Include()
, or do I have to do it manually?
我已经像这样设置了导航属性:
I've set up the navigation property like this:
public class MyUser : IdentityUser
{
public int? AddressId { get; set; }
[ForeignKey(nameof(AddressId))]
public virtual Address Address { get; set; }
}
public class Address
{
[Key]
public int Id { get; set; }
public string Street { get; set; }
public string Town { get; set; }
public string Country { get; set; }
}
推荐答案
不幸的是,您必须手动完成或创建您自己的 IUserStore
以在 中加载相关数据>FindByEmailAsync
方法:
Unfortunately, you have to either do it manually or create your own IUserStore<IdentityUser>
where you load related data in the FindByEmailAsync
method:
public class MyStore : IUserStore<IdentityUser>, // the rest of the interfaces
{
// ... implement the dozens of methods
public async Task<IdentityUser> FindByEmailAsync(string normalizedEmail, CancellationToken token)
{
return await context.Users
.Include(x => x.Address)
.SingleAsync(x => x.Email == normalizedEmail);
}
}
当然,仅仅为此实现整个商店并不是最好的选择.
Of course, implementing the entire store just for this isn't the best option.
不过,您也可以直接查询商店:
You can also query the store directly, though:
UserManager<IdentityUser> userManager; // DI injected
var user = await userManager.Users
.Include(x => x.Address)
.SingleAsync(x => x.NormalizedEmail == email);
这篇关于如何使用 UserManager 在 IdentityUser 上加载导航属性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!