0

I'm using EntityFramework 6. I would like to split my DbContext into multiple smaller ones. Edit: I have a single database I wish to connect to.

I will have a single DbContext with all the entities and migrations that only one central application will use. Other applications will use the smaller DbContext without migrations.

I have found that I need to inherit all DbContext from IdentityDbContext, even if they use none of it.

internal class SmallerDbContext : IdentityDbContext<ApplicationUser, 
ApplicationRole, int, ApplicationUserLogin, ApplicationUserRole, ApplicationUserClaim>
{
    public DbContext<Entity1> NotInSmallerDbContext { get; set; }
    public DbContext<Entity1> InSmallerDbContext { get; set; }
}

I would like this to be:

internal class SmallerDbContext : System.Data.Entity.DbContext
{
    public DbContext<Entity1> InSmallerDbContext { get; set; }
}

But this yields the following errors:

Paris.DAL.Repo.DbContext.ApplicationUserLogin: : EntityType 'ApplicationUserLogin' has no key defined. Define the key for this EntityType.
Paris.DAL.Repo.DbContext.ApplicationUserRole: : EntityType 'ApplicationUserRole' has no key defined. Define the key for this EntityType.
ApplicationUserLogins: EntityType: EntitySet 'ApplicationUserLogins' is based on type 'ApplicationUserLogin' that has no keys defined.
ApplicationUserRoles: EntityType: EntitySet 'ApplicationUserRoles' is based on type 'ApplicationUserRole' that has no keys defined.

I have tried to add these tables to the DbContext, but to no avail.

public IDbSet<ApplicationUser> Users { get; set; }
public IDbSet<ApplicationRole> Roles { get; set; }

Is there any way I can create DbContext that does not inherit from IdentityDbContext?

Diana Koenraadt
  • 319
  • 2
  • 11

1 Answers1

1

I was on the right path by adding the objects to the DbContext. You need to add only two, the User and UserLogin. The others are not needed.

    public DbSet<ApplicationUser> Users { get; set; }
    public DbSet<ApplicationUserLogin> UserLogins { get; set; }

Additionally, you need to set the correct table for both objects and you need to add some of virtual properties so that Entity Framework can handle these types as it would any of your other classes.

[Table("AspNetUsers")]
public class ApplicationUser : IdentityUser<int, ApplicationUserLogin, ApplicationUserRole, ApplicationUserClaim>
{
}


[Table("AspNetUserLogins")]
public class ApplicationUserLogin : IdentityUserLogin<int>
{
    [Key, Column(Order = 0)]
    public override string LoginProvider { get; set; }

    [Key, Column(Order = 1)]
    public override string ProviderKey { get; set; }

    [Key, Column(Order = 2)]
    public override int UserId { get; set; }
}

Now, your DbContext no longer has to inherit from IdentityDbContext.

Diana Koenraadt
  • 319
  • 2
  • 11