【发布时间】:2021-04-20 01:18:17
【问题描述】:
我与 ApplicationUser 有以下一对一的关系:
public class Person
{
public Guid PersonId { get; set; }
public string UserId { get; set; }
public string FirstName { get; set; }
public string LastName { get; set; }
public string Company { get; set; }
public string Role { get; set; }
public string Country { get; set; }
public DateTime CreatedDate { get; set; }
public bool IsActive { get; set; }
public ApplicationUser User { get; set; }
}
public class ApplicationUser : IdentityUser
{
public Guid PersonId { get; set; }
public string Provider { get; set; } = "LOCAL";
public string ExternalUserId { get; set; }
public Person Person { get; set; }
}
数据库上下文:
public class ApplicationDbContext : IdentityDbContext<ApplicationUser>
{
public ApplicationDbContext(DbContextOptions<ApplicationDbContext> opts) : base(opts) { }
public DbSet<Person> Person { get; set; }
public DbSet<ApplicationUser> User { get; set; }
protected override void OnModelCreating(ModelBuilder modelBuilder)
{
base.OnModelCreating(modelBuilder);
modelBuilder.ApplyConfiguration(new PersonConfiguration());
modelBuilder.Entity<ApplicationUser>(e => {
e.ToTable(name: "User");
e.HasOne(p => p.Person).WithOne(u => u.User);
//e.HasOne(p => p.Person).WithOne().HasForeignKey;
});
modelBuilder.Entity<IdentityRole>(e => e.ToTable(name: "Role"));
modelBuilder.Entity<IdentityUserRole<string>>(e => e.ToTable(name: "UserRole"));
modelBuilder.Entity<IdentityUserClaim<string>>(e => e.ToTable(name: "UserClaim"));
modelBuilder.Entity<IdentityUserLogin<string>>(e => e.ToTable(name: "UserLogin"));
modelBuilder.Entity<IdentityUserToken<string>>(e => e.ToTable(name: "UserToken"));
modelBuilder.Entity<IdentityRoleClaim<string>>(e => e.ToTable(name: "RoleClaim"));
}
}
人物实体配置:
public class PersonConfiguration : IEntityTypeConfiguration<Person>
{
public void Configure(EntityTypeBuilder<Person> builder)
{
builder.ToTable("Person");
builder.HasOne(u => u.User)
.WithOne(p => p.Person)
.HasForeignKey<Person>(p => p.UserId);
}
}
问题是当我从 db 获取人员数据时,即使使用 Include 扩展,相关用户也会返回 null。 仅供参考:我尝试使用 dbcontext 从 db 加载用户,但它也返回 null。
【问题讨论】:
-
尝试将
virtual添加到public Person Person { get; set; }。有关更多信息,请阅读此答案stackoverflow.com/questions/41881169/…
标签: c# asp.net-core entity-framework-core asp.net-identity