通过加入用户详细信息实体从IdentityDbContext获取用户详细信息

本文关键字:详细信息 用户 IdentityDbContext 获取 实体 | 更新日期: 2023-09-27 18:21:52

我有两个DB上下文。

它们是IdentityDbContext(由ApplicationDbContext引用)和DbEntites(即DbContext)。

IdentityDbContext仅用于身份验证和UserManager(不包含用户详细信息实体)。

DbEntites用于除User之外的其他实体(还包含User Details实体)。

IdentityDbContext

public class ApplicationUser : IdentityUser
{
   public int? ContactID { get; set; } // User Details Id
}
public class ApplicationDbContext : IdentityDbContext<ApplicationUser>
{
    public ApplicationDbContext()
        : base("DefaultConnection")
    {
        // I want to initialize the Login Entities Automatically So 
        //no Database.SetInitializer<ApplicationDbContext>(null); is used
    }
}

数据库实体

public class DBEntities : DbContext
{
    public DBEntities()
       : base("name=DefaultConnection")
   {
       Database.SetInitializer<DBEntities>(null);
   }
   public DbSet<Contact> Contacts { get; set; } // User Details Entity
}

现在我想列出ApplicationUser中的用户名,以及它们的详细信息,如DbEntites中的名称、地址等。

我试着把包括在内

public class ApplicationUser : IdentityUser
{
   public int? ContactID { get; set; }
   [ForeignKey("ContactID")]
   public Contact Contact { get; set; }
}
public DbSet<Contact> Contacts { get; set; }

到ApplicationDbContext,但每当我试图从ApplicationUser 获取数据时,它只会给我以下错误

The model backing the 'ApplicationDbContext' context has changed since the database was created.

我尝试将外键用于数据库中的ContactID。但仍然是同样的错误。我该如何解决问题?

请提供任何建议或解决方法。

更新:基本上,我只想在ApplicationDbContext中使用联系人实体,而不需要"自创建数据库以来,支持‘ApplicationDbContext’上下文的模型已经更改。"错误,并且仍然可以在DbEntites中使用它。

通过加入用户详细信息实体从IdentityDbContext获取用户详细信息

我通过为AspNetUsersAspNetRoles创建模型并在DbEntites中使用来解决问题。由于我的DbEntitesSetInitializer to null,它解决了我的问题。

public class AspNetUsers
{
    [Key]
    public string Id { get; set; }
    public string UserName { get; set; }
    public int? ContactID { get; set; }
    [ForeignKey("ContactID")]
    public Contact Contact { get; set; }
    public ICollection<AspNetRoles> Roles { get; set; } 
}
public class AspNetRoles
{
    [Key]
    public string Id { get; set; }
    public string Name { get; set; }
    public ICollection<AspNetUsers> Users { get; set; } 
}

在DbEntites 中

modelBuilder.Entity<AspNetUsers>()
                .HasMany(c => c.Roles)
                .WithMany(i => i.Users)
                .Map(t => t.MapLeftKey("UserId").MapRightKey("RoleId").ToTable("AspNetUserRoles"));

public DbSet<AspNetRoles> AspNetRoleses { get; set; }
public DbSet<AspNetUsers> AspNetUserses { get; set; }

这可能不是解决问题的理想方法,但到底是哪一种呢?