Search code examples
c#wpfentity-frameworkcode-first

WPF application with EF6 does not create new database in SQL Server Enterprise


I am working on a WPF application and using entity framework 6 code first for database but when I run the application, the database is not created in the SQL Server Enterprise. I googled a lot but could not find any suitable solution for this, I thank everyone in advance.

Below is my App.config file:

<?xml version="1.0" encoding="utf-8"?>
<configuration>
   <configSections>
       <!-- For more information on Entity Framework configuration, visit 
       http://go.microsoft.com/fwlink/?LinkID=237468 -->
    <section name="entityFramework"
      type="System.Data.Entity.Internal.ConfigFile.EntityFrameworkSection, EntityFramework, 
       Version=6.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089"
      requirePermission="false"/>    
   </configSections>

   <connectionStrings>
         <add name="DbConnectionString" connectionString="Data Source=.;Initial 
         Catalog=CricketAcademy;Integrated Security=True;" providerName="System.Data.SqlClient" />
   </connectionStrings>


   <startup> 
       <supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.5.2"/>
   </startup>
   <entityFramework>
       <providers>
           <provider invariantName="System.Data.SqlClient" 
           type="System.Data.Entity.SqlServer.SqlProviderServices, EntityFramework.SqlServer"/>
       </providers>
   </entityFramework>
  </configuration>  

This is my Context Class:

class Db : DbContext
{
    public Db() : base("name=DbConnectionString")
    {

    }
    public DbSet<Player> Players { get; set; }
    public DbSet<Player_Phone> PlayerPhones { get; set; }
    public DbSet<Admission> Admissions { get; set; }
    public DbSet<Fee> Fees { get; set; }
    public DbSet<Coach> Coaches { get; set; }
    public DbSet<Shift> Shifts { get; set; }

}  

And here is my MainWindow class:

public partial class MainWindow : Window
{
    private Db DB = new Db();
    public MainWindow()
    {
        InitializeComponent();
    }

    private void button_Click(object sender, RoutedEventArgs e)
    {

    }

    private void Window_Loaded(object sender, RoutedEventArgs e)
    {

    }
}

Solution

  • Add in the constructor of your DbContext:

    public Db() : base("name=DbConnectionString")
    {
          Database.SetInitializer<Db>(new CreateDatabaseIfNotExists<Db>());
    }
    

    You can find more information in this article.