Combine my ApplicationsDbContext with IdentityDbCo

2019-05-18 18:08发布

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.

2条回答
Melony?
2楼-- · 2019-05-18 19:02

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 });
    }
查看更多
男人必须洒脱
3楼-- · 2019-05-18 19:11

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.

查看更多
登录 后发表回答