Entity Framework Not Creating Database

34,247

Solution 1

Asked around on the MSDN forums instead, and got a satisfactory answer:

Entity Framework will not create a database until first access. The current code block in Application_Start() only specifies the strategy to use when creating the database during first access.

To trigger creation of the database on startup, an instance of the database context must be created, and context.Database.Initialize(true) must be invoked.

Solution 2

I have the same issue and found a elegant solution: call the SetInitializer in the constructor of your DbContext:

public class MyDbContext : DbContext
{
   protected MyDbContext : this("MyConnection")
   {
       Database.SetInitializer<MyDbContext>(new CreateDatabaseIfNotExists<MyDbContext>());
   }
}

My app setting:

<connectionStrings>
    <add
      name="MyConnection"
      connectionString="Data Source=(LocalDb)\v11.0;AttachDbFilename=|DataDirectory|\MyDB.mdf;Initial Catalog=MyDB;Integrated Security=True"
      providerName="System.Data.SqlClient" />
  </connectionStrings>

Solution 3

I know this was already answered by mazatsushi in the rightest way. But just to clarify it to begginers: Based in mazatsushi's answer what you have to do is to write:

        Database.SetInitializer(new DropCreateDatabaseIfModelChanges<SorteoContext>());
        using (var context = new SorteoContext())
        {
            context.Database.Initialize(force: true);
        }

inside Application_Start() function in Global.asax.cs and Boom! works!

Share:
34,247
mazatsushi
Author by

mazatsushi

Updated on April 22, 2020

Comments

  • mazatsushi
    mazatsushi about 4 years

    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) does not automatically create the table mapping on application startup. Any ideas on how to make it do so?

    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; }
        }
    }
    

    I've added a 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);
    }
    
  • Luis Tellez
    Luis Tellez over 10 years
    If i could vote more than once for this i would... Was trying to do a Database-Update and kept getting the error about no database and just needed to run the application once
  • Rahatur
    Rahatur over 9 years
    I think this will not compile as it will have error: protected MyDbContext : this("MyConnection")
  • Maksood
    Maksood about 9 years
    'MyConnection' is a config entry
  • Hywel Rees
    Hywel Rees about 8 years
    I think he was referring to the 'this' bit. It should be base("MyConnection")