【问题标题】:Identity user object is not mapped to another object - entity framework身份用户对象未映射到另一个对象 - 实体框架
【发布时间】:2020-05-16 21:51:22
【问题描述】:

因此,我使用 ASP.Identity 和 EntityFramework 使用代码优先方法制作了 .NET Core 应用程序。 我的 AppUser 类:

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

然后我有附加 AppUser 的 Notice.cs 类

    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 表有适当的 AppUserId 列和正确的 ID。但是,每次我尝试从数据库上下文访问通知的 AppUser 属性时,它总是为空。我该如何解决?谢谢!

【问题讨论】:

    标签: c# sql-server entity-framework .net-core asp.net-identity


    【解决方案1】:

    你没有显示你是如何从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
    
    

    【讨论】:

    • 好的,我是通过存储库进行的,确实没有加入该属性。我很清楚,谢谢!
    【解决方案2】:

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

    在您的 AppUser 类中,尝试添加:

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

    这应该允许实体框架识别关系的双方。

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

    【讨论】:

    • 我尝试将它添加到 AppUser 类,然后当我尝试进行迁移时,他没有看到 db 结构有任何变化。所以我删除了整个数据库和迁移并开始了初始迁移。而且我仍然无法从通知实体访问 AppUser。 AppUserId 外键位于 Notice 表中,并且已正确分配 - 与之前相同:/
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-10-31
    • 2015-12-02
    • 2013-04-13
    • 1970-01-01
    相关资源
    最近更新 更多