Mark
Mark

Reputation: 1569

Entity Framework 4.1 Code First not creating tables

I am using EF 4.1 and have created a repository using DBContext etc. Connection string set to point to a SQL Server 2008 R2 Dev edition.

When I run a console app that calls my gateway which in turn adds an entity and saves, an exception is thrown saying it can't find the table. When I look at my db, there is a database created but there are no tables created automatically except EmdMetadata.

Am I missing something?

Mark

Upvotes: 10

Views: 22381

Answers (4)

shuniar
shuniar

Reputation: 2622

To set the auto drop and create you would do something like this...

public class MyDbContext : DbContext 
{
    public IDbSet<Foo> Foos { get; set; }

    protected override void OnModelCreating(DbModelBuilder modelBuilder)
    {
        Database.SetInitializer(new MyDbContextInitializer());

        base.OnModelCreating(modelBuilder);
    }
}

public class MyDbContextInitializer : DropCreateDatabaseIfModelChanges<MyDbContext>
{
    protected override void Seed(MyDbContext dbContext)
    {
        // seed data

        base.Seed(dbContext);
    }
}

Upvotes: 8

Ricardo Peres
Ricardo Peres

Reputation: 14555

Better: add the initializer to the static constructor, like this:

public class MyDbContext : DbContext 
{
    static MyDbContext()
    {
        Database.SetInitializer(new MyDbContextContextInitializer());
    }
}

Upvotes: 1

Simon
Simon

Reputation: 415

You need to add this to your Application_Start()

 Database.SetInitializer(new MyDbContextContextInitializer());
 var context = new MyDbContextContext();
 context.Database.Initialize(true);

The last line forces the DB to created

Upvotes: -1

iandotkelly
iandotkelly

Reputation: 9134

You can create the tables yourself - the easiest way is:

IObjectContextAdapter adapter = (IObjectContextAdapter)context;
string script = adapter.ObjectContext.CreateDatabaseScript();
context.Database.ExecuteSqlCommand(script);

Where context is my EF 4.1 database context. Prior to this code I drop all the tables (from the last time I created the db), and after this I seed it with data.

Upvotes: 8

Related Questions