Petter Petter
Petter Petter

Reputation: 103

How to create the database when using code first

I'm doing code first approach for the first time, and I created two classes (tables), and a context class.

Context

namespace Idle.Models.Database
{
    public class DatabaseContext : DbContext
    {
        public DatabaseContext() : base("name=Database") 
        {
        }

        public DbSet<Company> Companies{ get; set; }
        public DbSet<Car> Cars{ get; set; }
    }
}

And then I built the project.

But the tables weren't created in my database.

How do I then create my two tables?

Upvotes: 1

Views: 51

Answers (1)

Bassam Alugili
Bassam Alugili

Reputation: 17003

1) Magic creation, just create your DbContext:

Database.SetInitializer(new DropCreateDatabaseAlways<DatabaseContext >());

using (var databaseContext = new DatabaseContext ())
{
   // Do any stuff here
   databaseContext .SaveChanges();
   Console.WriteLine("Done");
}

2) If you want to use DbMigration: In Nuget console you have to use the command Add-Migration/Update-Migration More info:

https://msdn.microsoft.com/en-us/data/jj591621.aspx

Upvotes: 1

Related Questions