Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

like image 540
Mark Avatar asked Aug 30 '11 21:08

Mark


People also ask

Which is better code first or database first in Entity Framework?

Versioning databases is hard, but with code first and code first migrations, it's much more effective. Because your database schema is fully based on your code models, by version controlling your source code you're helping to version your database.

Can we create table without primary key in Entity Framework code First?

The Entity framework will not support to have a table without primary key, but we can overcome this issue by accessing the table with additional column via a view and marking the new column as Primary in entity framework. Entity Framework requires primary keys for entities.


2 Answers

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);
    }
}
like image 87
shuniar Avatar answered Oct 19 '22 16:10

shuniar


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.

like image 41
iandotkelly Avatar answered Oct 19 '22 17:10

iandotkelly