Search code examples
wpfef-code-firstsql-server-ce-4

What can I do to generate the DB in EF Code First?


I am not planning to use EF Code First in an MVC Website. I am looking to Utilize it in a App that has a WPF Client.

Projects are setup as

  • ContactManager.Core // Contains all
    Entities(dll)
  • ContactManager.Data // Contains the DataContext and other data related Services(dll)
  • ContactManager.Services // Business
    components (dll)
  • ContactManager.Client // WPF
    Application

I am unable to generate a SQLExpress or SQLCE 4.0 DB. I am more interested in compact version db. I am not getting any error except my unit tests fail because it tries to connect a db that doesnt exist.


Solution

  • I found out the answer 2 Options:

    Option 1:

    In your DbContext you specify the connection strings in the base constructor:

    public class RecetteContext : DbContext
    {
        public RecetteContext()
            :base("<YourConnectionString HERE>")
        {
        }
    
        public DbSet<Categorie> Categories { get; set; }
        public DbSet<Recette> Recettes { get; set; }
    
        }
    }
    

    Option 2:

    The one I used, you give you connection string a name in the DbContext base constructor:

    public RecetteContext()
        : base("RecettesDatabase")
    {            }
    

    And in your App.Config file you add a ConnectionString with the same name:

    <?xml version="1.0" encoding="utf-8"?>
    <configuration>
      <connectionStrings>
        <add name="RecettesDatabase"
             connectionString="Data Source=RecettesDB.sdf"
             providerName="System.Data.SqlServerCe.4.0"/>
      </connectionStrings>
    </configuration>
    

    Hope it solved your issue!