none
EF 4.1 Not Creating Database/Tables RRS feed

  • Question

  • Hi,

    Been playing around with the Code First feature of Entity Framework 4.1 using an ASP.NET MVC 3 project.

    However the database (SQL Server 2008 R2 Enterprise) does not automatically create the database & table(s) on application startup. Would greatly appreciate some guidance here.

    The project has only one POCO:

    namespace RIS.Models
    {
     public class Person
     {
     [Key]
     public virtual string NRIC { get; protected set; }
     public virtual string FirstName { get; protected set; }
     public virtual string MiddleName { get; protected set; }
     public virtual string LastName { get; protected set; }
     }
    }
    
    

    It also has the following database context class:

    namespace RIS.Models
    {
     public class RIS_DB : DbContext
     {
     public DbSet<Person> People { get; set; }
     }
    }
    

    An SQL connection string to the global web.config file as follows:
    <add name="RIS_DB" connectionString="Data Source=URAHARA-PC;Initial Catalog=RIS_DB;
    Integrated Security=SSPI;Pooling=False" providerName="System.Data.SqlClient"/>
    

    There is also an explicit instruction to create the database if it does not exist in the Global.asax.cs file:

    protected void Application_Start()
    {
     Database.SetInitializer(new CreateDatabaseIfNotExists<RIS_DB>());
    
     AreaRegistration.RegisterAllAreas();
    
     RegisterGlobalFilters(GlobalFilters.Filters);
     RegisterRoutes(RouteTable.Routes);
    }
    

    Tuesday, July 5, 2011 2:23 PM

Answers

  • Hello,

    EF will not create database unless it has to use it for the first time. The code you are using in the Application_Start will only tell EF what strategy it should use once it tries to create the database. If you want to trigger initialization immediately during Application_Start you must create context instance and call context.Database.Initialize(true); It will run your configured initializer immediately.

    Best regards,
    Ladislav

    • Marked as answer by mazatsushi Wednesday, July 6, 2011 3:19 AM
    Tuesday, July 5, 2011 10:30 PM

All replies

  • Hello,

    EF will not create database unless it has to use it for the first time. The code you are using in the Application_Start will only tell EF what strategy it should use once it tries to create the database. If you want to trigger initialization immediately during Application_Start you must create context instance and call context.Database.Initialize(true); It will run your configured initializer immediately.

    Best regards,
    Ladislav

    • Marked as answer by mazatsushi Wednesday, July 6, 2011 3:19 AM
    Tuesday, July 5, 2011 10:30 PM
  • Hi Ladislav

    Tried it out, and worked like a charm.

    Cheers!

    Wednesday, July 6, 2011 3:19 AM