Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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();
    }
}
like image 678
Old Geezer Avatar asked Feb 11 '15 07:02

Old Geezer


People also ask

How do I import multiple tables from another database?

Project -> Add New Item… Select Data from the left menu and then ADO.NET Entity Data Model Select the connection to the database you created in the first section and click Next Click the checkbox next to Tables to import all tables and click Finish

How to add a model to a dbcontext?

Just create your new table as a model and add its entry in DbContext class public class TestingContext : DbContext, IDisposable { public DbSet<CallDataRecord> CallDataRecords { get; set; } public DbSet<Attempt> Attempts { get; set; } public DbSet<MyNewModel> MyNewModels { get; set; } In case it helps someone else, I'll mention my facepalm.

How do I update a database with a new table?

For anyone looking to update a database with a new table (say I want to add an UserAttachment table to sit alongside my existing User table) using EF code first, do the following: With automatic migrations enabled you should ensure you have... 1.) Create your new model as you see fit. 2.)

How do I create a connection to a database using dbcontext?

The DbContext class will do all the hard work for us. It will establish a connection to the database. The only thing we need to do here is inherit our StudentCourseContext from the DbContenxt class and add a connection string in the root web.config file.


1 Answers

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();
}
}
like image 180
Nazmul Hossain Avatar answered Nov 16 '22 03:11

Nazmul Hossain