首页 文章

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

提问于
浏览
1

我有两个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
    }
}

DBEntities

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

现在我想列出ApplicationUser中的UserNames以及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 . 但仍然是同样的错误 . 我该如何解决这个问题?

请提出任何建议或解决方法 .

Update: 基本上我只想在ApplicationDbContext中使用 Contact Entity,而不会出现"The model backing the 'ApplicationDbContext' context has changed since the database was created."错误,并且仍然可以在DbEntites中使用它 .

1 回答

  • 0

    我通过为 AspNetUsersAspNetRoles 创建模型并在 DbEntites 中使用来解决问题 . 由于我的 DbEntites 已经 SetInitializer 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; }
    

    这可能不是解决问题的理想方法,但反正哪一个?

相关问题