本文介绍了如何使用UserManager在IdentityUser上加载导航属性的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我已经扩展了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<IdentityUser>并在其中将相关数据加载到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上加载导航属性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

10-28 11:29