EF 6 Code-First not creating one table

c# ef-code-first entity-framework-6

Question

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:

  • The table does exists in the edmx model.
  • The model .tt file does generate the class for the table.
  • The context .tt file does generate a DbSet for the table.
  • I've removed my edmx model and recreated from the database.

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:

enter image description here

1
1
7/14/2015 1:52:13 PM

Accepted Answer

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...

  • Add a PK to underlying table (original mapped to edmx)
  • Refresh edmx model
  • Now dbContext.Database.Create(); creates the table succesfully.
0
7/14/2015 2:17:52 PM


Related Questions





Related

Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow