我已经扩展了IdentityUser以包括用户地址的导航属性,但是当使用UserManager.FindByEmailAsync为用户提供服务时,不会填充该导航属性。 ASP.NET Identity Core是否具有某种方法来填充诸如Entity Framework的Include()之类的导航属性,还是我必须手动进行?

我已经这样设置了导航属性:

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<IdentityUser>,并在其中将相关数据加载到FindByEmailAsync方法中:

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);
    }
}

当然,仅为此目的实现整个商店并不是最佳选择。

您也可以直接查询商店,但是:
UserManager<IdentityUser> userManager; // DI injected

var user = await userManager.Users
    .Include(x => x.Address)
    .SingleAsync(x => x.NormalizedEmail == email);

关于c# - 如何使用UserManager在IdentityUser上加载导航属性,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/48623533/

10-10 15:33