I'm a little stuck with EF Code-first to create a new database. We have an existing database and used the Model-First approach successfully. Now I would like to existing model to create a new database at run-time like this:
public class DatabaseInitializer : IDatabaseInitializer<MDREntities>
{
public void InitializeDatabase(MDREntities dbContext)
{
if (dbContext.Database.Exists())
{
// Delete the existing database
dbContext.Database.ExecuteSqlCommand(TransactionalBehavior.DoNotEnsureTransaction, "ALTER DATABASE [" + dbContext.Database.Connection.Database + "] SET SINGLE_USER WITH ROLLBACK IMMEDIATE");
dbContext.Database.Delete();
}
// Create new database
dbContext.Database.Create();
// Add initial data
addMasterData(dbContext);
// Commit changes.
dbContext.SaveChanges();
}
}
The above runs through successfully and all my tables are created except for 1.
I've done the following without any luck:
Is it possible to "trace" what dbContext.Database.Create();
does and if something did in fact go wrong?
I also noticed that the "missing" table is the only one with a composite PK, could this be a problem?
Update:
When I had a look at SQL Profiler
, I found this comment saying that the table is ignored. Unfortunately it doesn't say why:
-- Ignoring entity set with defining query: [MDRModelStoreContainer].[tblRelatedPatient]
Here's the table mapped in the edmx:
The original table did not have a Primary Key.
Even though the edmx showed a Composite Primary Key
in the designer, the table did not get created successfully from the edmx Model until I actually updated the original database and refreshed the edmx, strange...
dbContext.Database.Create();
creates the table succesfully.