Reputation: 12745
I am using entity framework code first approach and have following model and db context.
public class Patient
{
public int Id { get; set; }
public string FirstName { get; set; }
}
public class PatientContext:DbContext
{
public DbSet<Patient> Persons { get; set; }
}
Now to have the model created in database I have to Run Enable Migration
and if any changes then have to run Update database
using package manager console.
But is there any way I can do that using code. So when ever some one run console application it will create all table schema.
class Program
{
static void Main(string[] args)
{
//Code to Create my tables
//Something similar to enable migration and update database
}
}
I can have a record created inside main app and that will create the table structure, but creating an record to create table structure seems redundant. Also , if there are any mode changes, following code will throw an exception.
Is there a better approach?
static void Main(string[] args)
{
using (PatientContext pcontext = new DatabaseMigApp.PatientContext())
{
pcontext.Patients.Add(new Patient() { FirstName = "Steve",Id = 1});
pcontext.SaveChanges();
}
}
Upvotes: 1
Views: 766
Reputation: 2603
Yes, there is. You will have to run Enable-Migrations –EnableAutomaticMigrations from package manager console first, so that it generates a Configuration class as follows:
internal sealed class Configuration : DbMigrationsConfiguration<DatabaseMigApp.PatientContext>
{
public Configuration()
{
AutomaticMigrationsEnabled = true;
}
protected override void Seed(DatabaseMigApp.PatientContext context)
{
}
}
Then you may update the Program.cs as follows to automatically migrate to the latest version based on your model changes:
using System.Data.Entity;
class Program
{
static void Main(string[] args)
{
using (PatientContext pcontext = new DatabaseMigApp.PatientContext())
{
Database.SetInitializer(new MigrateDatabaseToLatestVersion<PatientContext, Configuration>());
pcontext.Database.Initialize(true);
}
}
}
If you do not wish to use automatic migrations and generate them manually (for more control), you could turn off the automatic migrations and add-migration each time you change your model. The code in the program.cs would still suffice to update your database when you run the console application.
Read more about automatic migrations here
Upvotes: 3