Thursday, January 22, 2015

In MVC5, How to merge the IdentityDbContext into custom db context

Here is the code as an example,

1. Add the custom user login and user role configurations

    public class IdentityUserLoginConfiguration : EntityTypeConfiguration<IdentityUserLogin>
    {
        public IdentityUserLoginConfiguration()
        {
            HasKey(iul => iul.UserId);
        }
    }
    public class IdentityUserRoleConfiguration : EntityTypeConfiguration<IdentityUserRole>
    {
        public IdentityUserRoleConfiguration()
        {
            HasKey(iur => iur.RoleId);
        }
    }

2. Inherit your custom dbcontext from IdentityDbContext,

    public class CustomDbContext : IdentityDbContext<ApplicationUser>
    { public CustomDbContext() : base("DefaultConnection")
        {
        }
        public DbSet<CustomEntity> Entities { get; set; }
        protected override void OnModelCreating(DbModelBuilder modelBuilder)
        {
            modelBuilder.Conventions.Remove<PluralizingTableNameConvention>();
            modelBuilder.Configurations.Add(new IdentityUserLoginConfiguration());
            modelBuilder.Configurations.Add(new IdentityUserRoleConfiguration());
        }
    }

No comments: