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

Old Geezer picture Old Geezer · Feb 11, 2015 · Viewed 11.5k times · Source

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();
    }
}

Answer

Nazmul Hossain picture Nazmul Hossain · Feb 11, 2015

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();
}
}