【问题标题】:Get User Details From IdentityDbContext by joining to User Details entity通过加入用户详细信息实体从 IdentityDbContext 获取用户详细信息
【发布时间】:2014-11-08 01:39:50
【问题描述】:

我有两个数据库上下文。

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

IdentityDbContext 仅用于 Authentication 和 UserManager(不包含用户详细信息实体)。

DbEntites 用于除用户之外的其余实体(还包含用户详细信息实体)。

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 中使用 Contact 实体,而没有“支持 'ApplicationDbContext' 上下文的模型在创建数据库后发生了变化。 "错误,仍然可以在 DbEntites 中使用它。

【问题讨论】:

    标签: c# asp.net-mvc entity-framework asp.net-mvc-5


    【解决方案1】:

    我通过为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; } 
    }
    

    在数据库实体中

    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; }
    

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2014-03-30
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-06-11
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多