Combine my ApplicationsDbContext with IdentityDbContext no key defined using MVC 5

心已入冬 提交于 2019-12-07 22:53:57

问题


I was combining my existing DBContext with the new IdentityDbContext in MVC 5. I managed to combine the two contexts but when I ran my application and the model was being created I was presented with the following error message:

Context.IdentityUserLogin: : EntityType 'IdentityUserLogin' has no key defined. Define the key for this EntityType. Context.IdentityUserRole: : EntityType 'IdentityUserRole' has no key defined. Define the key for this EntityType.


回答1:


I worked out how to fix it after doing a bit of reading.

Create the two following configuration classes (keeps it clean in your OnModelCreating method as your database grows and relationships between tables increase)

public class IdentityUserLoginConfiguration : EntityTypeConfiguration<IdentityUserLogin>
{

    public IdentityUserLoginConfiguration()
    {
        HasKey(iul => iul.UserId);
    }

}

public class IdentityUserRoleConfiguration : EntityTypeConfiguration<IdentityUserRole>
{

    public IdentityUserRoleConfiguration()
    {
        HasKey(iur => iur.RoleId);
    }

}

In the OnModelCreating method within your Applications DbContext add the two configurations outlined above to the model:

protected override void OnModelCreating(DbModelBuilder modelBuilder)
    {

        modelBuilder.Configurations.Add(new IdentityUserLoginConfiguration());
        modelBuilder.Configurations.Add(new IdentityUserRoleConfiguration());

    }

This should now get rid of the error methods when your model is being created. It did for me.




回答2:


Don't bother with the configuration classes.

protected override void OnModelCreating(DbModelBuilder modelBuilder)
    {
        modelBuilder.Entity<IdentityUserLogin>().HasKey<string>(l => l.UserId);
        modelBuilder.Entity<IdentityRole>().HasKey<string>(r => r.Id);
        modelBuilder.Entity<IdentityUserRole>().HasKey(r => new { r.RoleId, r.UserId });
    }


来源:https://stackoverflow.com/questions/20912704/combine-my-applicationsdbcontext-with-identitydbcontext-no-key-defined-using-mvc

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!