Search code examples
asp.net-mvcentity-frameworkef-code-firstasp.net-identityasp.net-identity-2

MVC/Code First: how to add more tables to the same db context?


I am using the standard MVC template that comes with VS 2013. It has a neat membership provider that makes using external logins (Google, Facebook etc) a breeze. There are also tutorials on how to extend the IdentityUser model to add new properties such as date of birth.

I would like to add more tables (of my application) to the already coded database context so as to enjoy the same code first migration features. How do I do it? The current db context is defined as follows:

public class ApplicationDbContext : IdentityDbContext<ApplicationUser>
{
    public ApplicationDbContext()
        : base("DefaultConnection", throwIfV1Schema: false)
    {
    }
    public static ApplicationDbContext Create()
    {
        return new ApplicationDbContext();
    }
}

Solution

  • you are using asp.net MVC5 identity 2 then ApplicationDbContext already there in IdentityModels.cs .So you can add table (DbSet) like this.

     public class ApplicationDbContext : IdentityDbContext<ApplicationUser>
    {
    public ApplicationDbContext()
        : base("ApplicationDbContext", throwIfV1Schema: false)
    {
    }
    
    public DbSet<Department> Departments { get; set; }
    public DbSet<Student> Students { get; set; }
    
    public static ApplicationDbContext Create()
    {
        return new ApplicationDbContext();
    }
    }