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();
}
}
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
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.
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.)
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.
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();
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With