asp.net 核心身份自定义用户数据与集合
asp.net core identity custom user data with a collection
public class ApplicationUser : IdentityUser
{
public ICollection<Profile> Profiles { get; set; }
}
我在 ApplicationUser 中有一组配置文件。
我在方法 GetProfileDataAsync
中创建了自定义 ProfileService
var user = await _userManager.GetUserAsync(principal);
user.Profiles returns 空值。在添加到 ClaimPrincipals 之前,它必须在某处获取用户数据。
如何自定义 Asp.Net Core Identity 中的某处以在获取用户时加载配置文件。
在 属性 的情况下,例如,ContractName。有效。
您需要使用Include
如下:
var userId = User.FindFirstValue(ClaimTypes.NameIdentifier);
_userManager.Users.Where(u => u.Id = userId).Include(u => u.Profiles).FirstOrDefaultAsync();
How can I customize somewhere in Asp.Net Core Identity to load Profiles when getting User
Asp.Net Core Identity 是抽象系统,没有 loading related data 的概念,这是 EF(核心)概念,因此无法在该级别配置。
5.0 之前的 EF Core 版本也没有“自动预加载”导航的概念 属性(至少不是官方的)。因此,您必须配置延迟加载(具有所有相关的缺点),或者发出额外的手动预加载查询,如另一个答案所示。
EF Core 5.0 提供了一种方法来配置导航 属性 以使用新的 Navigation
and AutoInclude
fluent APIs:
自动预先加载
protected override void OnModelCreating(ModelBuilder modelBuilder)
{
base.OnModelCreating(modelBuilder);
modelBuilder.Entity<ApplicationUser>()
.Navigation(e => e.Profiles)
.AutoInclude();
}
在EF Core3.x中,虽然官方没有公布,也没有fluentAPI可用,但是同样可以配置SetIsEagerLoaded元数据API:
modelBuilder.Entity<ApplicationUser>()
.Metadata.FindNavigation(nameof(ApplicationUser.Profiles))
.SetIsEagerLoaded(true);
public class ApplicationUser : IdentityUser
{
public ICollection<Profile> Profiles { get; set; }
}
我在 ApplicationUser 中有一组配置文件。
我在方法 GetProfileDataAsync
ProfileService
var user = await _userManager.GetUserAsync(principal);
user.Profiles returns 空值。在添加到 ClaimPrincipals 之前,它必须在某处获取用户数据。
如何自定义 Asp.Net Core Identity 中的某处以在获取用户时加载配置文件。
在 属性 的情况下,例如,ContractName。有效。
您需要使用Include
如下:
var userId = User.FindFirstValue(ClaimTypes.NameIdentifier);
_userManager.Users.Where(u => u.Id = userId).Include(u => u.Profiles).FirstOrDefaultAsync();
How can I customize somewhere in Asp.Net Core Identity to load Profiles when getting User
Asp.Net Core Identity 是抽象系统,没有 loading related data 的概念,这是 EF(核心)概念,因此无法在该级别配置。
5.0 之前的 EF Core 版本也没有“自动预加载”导航的概念 属性(至少不是官方的)。因此,您必须配置延迟加载(具有所有相关的缺点),或者发出额外的手动预加载查询,如另一个答案所示。
EF Core 5.0 提供了一种方法来配置导航 属性 以使用新的 Navigation
and AutoInclude
fluent APIs:
protected override void OnModelCreating(ModelBuilder modelBuilder)
{
base.OnModelCreating(modelBuilder);
modelBuilder.Entity<ApplicationUser>()
.Navigation(e => e.Profiles)
.AutoInclude();
}
在EF Core3.x中,虽然官方没有公布,也没有fluentAPI可用,但是同样可以配置SetIsEagerLoaded元数据API:
modelBuilder.Entity<ApplicationUser>()
.Metadata.FindNavigation(nameof(ApplicationUser.Profiles))
.SetIsEagerLoaded(true);