标识用户对象未映射到另一个对象 - entity framework

Identity user object is not mapped to another object - entity framework

所以我使用代码优先方法使用 ASP.Identity 和 EntityFramework 制作了 .NET Core 应用程序。 我的 AppUser class:

public class AppUser : IdentityUser<string>
{
    public string Name { get; set; }
    public string Surname { get; set; }
    public DateTime DateJoined { get; set; }
}

然后我有 Notice.cs class 附加了 AppUser

    public class Notice
{
    //... some other props
    public string Description { get; set; }
    public DateTime DatePosted { get; set; }
    public AppUser AppUser { get; set; }
}

还有我的 applicationDbContext

 public class ApplicationDbContext : IdentityDbContext<AppUser, Role, string>
{
    public ApplicationDbContext(DbContextOptions<ApplicationDbContext> options) 
        : base(options)
    {

    }
    protected override void OnModelCreating(ModelBuilder builder)
    {
        builder.Entity<Notice>()
            .Property(p => p.NoticeId)
            .ValueGeneratedOnAdd();

        builder.Entity<AppUser>()
            .Property(p => p.Id)
            .ValueGeneratedOnAdd();
        builder.Entity<Role>()
            .Property(p => p.Id)
            .ValueGeneratedOnAdd();
    }
    public DbSet<Notice> Notices { get; set; }
}

将通知播种到数据库并将用户分配给它们后,我无法访问 AppUser 属性。 我查看了数据库,发现 Notices table 具有包含正确 ID 的适当 AppUserId 列。但是,每次我尝试从数据库上下文访问 Notice 的 AppUser 属性 时,它始终为空。我该如何解决?谢谢!

你创造了一种Entity Framework不知道如何处理的单向关系。我假设如果您查看数据库,您将不会在表中看到外键。

给您的 AppUser class,尝试添加:

Public ICollection<Notice> Notices { get; set; }

这应该允许 entity framework 识别关系的双方。

我假设每个应用程序用户可能有很多通知。

你没有说明你是如何从 Notice 访问 AppUser 的,如果它类似于:

var notice = dbContext.Notices
                 .First(n => n.NoticeId == id); // get the notice without AppUser

那么 notice.AppUser 将是 null,因为您没有明确地将 属性 添加到结果中。

你可以这样实现:

var notice = dbContext.Notices
                 .Include(n => n.AppUser)
                 .First(n => n.NoticeId == id); // get the notice with AppUser