Seth
Seth

Reputation: 8373

Refactoring Database with EntityFramework from code

I'm in the process of adapting the MVCMusicStore shopping cart. I wish to refactor the database using EntityFramework - not via the Server Explorer.

In my models folder I created a new FooEntities model.

public class FooStoreEntities : DbContext
{
    public DbSet<Foo> Foos { get; set; }
    public DbSet<Category> Categories { get; set; }
    public DbSet<FooMaker> FooMakers { get; set; }
    public DbSet<Cart> Carts { get; set; }
    public DbSet<Order> Orders { get; set; }
    public DbSet<OrderDetail> OrderDetails { get; set; }
}

I've also created the extra models Foo, FooMaker and Category. The other models already existed in the MVCMusicStore example.

I created a SampleFooData class which inherits from DropCreateDatabaseIfModelChanges<FooStoreEntities> and overrides the seed method to seed the new tables.

I changed the Application_Start method in the Global.asax.cs to contain System.Data.Entity.Database.SetInitializer(new FooStore.Models.SampleFooData());

In the web.config file I have:

<connectionStrings>
    <add name="FooStoreEntities"
    connectionString="Data Source=|DataDirectory|FooStore.sdf"
    providerName="System.Data.SqlServerCe.4.0"/>
</connectionStrings>

Where FooStore.sdf still contains all the old tables from the MVCMusicStore application.

When I execute the web app it hits the SetInitializer breakpoint however it does not seem to create the SampleFooData object and create the new tables in the database. What am I missing? Or is there something fundamental I don't understand?

Upvotes: 4

Views: 498

Answers (1)

woggles
woggles

Reputation: 7444

It will only be created when you use your DB context: see Entity Framework Database.SetInitializer simply not working

You could put

var ctx = new FooStoreEntities();
ctx.Database.Initialize(true);

after where you set the initializer in Application_Start.

Upvotes: 2

Related Questions