[Notes] Entity Framework - Code First on SQL Compact/LocalDB


PM> Install-Package NuSpec
         Powershell cmdlet that makes working with NuSpec files easier!


1. Select your CodeFirst project , the project should contains class inherit from DBContext class

2. PM> Install-Package EntityFramework
    PM> Install-Package EntityFramework.SqlServerCompact  (if you use SQL CE)

3. PM> Enable-Migrations
    PM> Enable-Migrations -Force (To overwrite the existing migrations configuration)

4. PM> Add-Migration Migrations-InitDB
Command return :
The Designer Code for this migration file includes a snapshot of your current Code First model.
This snapshot is used to calculate the changes to your model when you scaffold the next migration.
If you make additional changes to your model that you want to include in this migration, then you can re-scaffold it by running 'Add-Migration Migrations-InitDB' again.
5. PM> Update-Database -Verbose


  • Hit "Tab" to get NuGut command completion.  e.g. "Ebalbe-M" > “Enable-Migrations”
  • Connection String, Reference : http://msdn.microsoft.com/en-us/library/jj653752(v=vs.110).aspx
    1. Microsoft SQL Server Compact (SQL CE)
      <add name="CodeFirstContext" providerName="System.Data.SqlServerCe.4.0" connectionString="Data Source=|DataDirectory|localdb.sdf"/>
      <add name="CodeFirstContext" providerName="System.Data.SqlServerCe.4.0" connectionString="Data Source=E:\MSSQL-CE\localdb.sdf"/>
    2. Microsoft SQL Server 2012 Express LocalDB
      <add name="CodeFirstContext"
      providerName="System.Data.SqlClient" connectionString="Data Source=(LocalDB)\v11.0;AttachDbFileName=|DataDirectory|\DatabaseFileName.mdf;Integrated Security=True;MultipleActiveResultSets=True" />
      <add name="CodeFirstContext"
      providerName="System.Data.SqlClient" connectionString="Data Source=(LocalDB)\v11.0;AttachDbFileName=E:\MSSQL-LocalDB\DatabaseFileName.mdf;Integrated Security=True;MultipleActiveResultSets=True" />

  • Note 1: If your StartUp project is web Project, DataDirectory folder is .\App_Data\ 
  • Note 2: If want to see SQL CE in VS, need install entenstion "SQL Server Compact Toolbox".
  • Note 3: SQL Compact 4 has full support for Entity Framework, Linq to SQL
  • Note 4: SQL LocalDB default server is “(LocalDb)\v11.0”