Pages

Friday, May 27, 2011

Code-First, EF 4.1, SQL Compact

Entity Framework 4.1 now fully supports SQL Server Compact for Code-First Development with ASP.NET MVC 3. There are a few gotchas still, especially considering that CTP versions of libraries had workarounds and are therefore incompatible with the RTM. But since they are still available as NuGet packages, this might be confusing for the beginners. It certainly was for me.

So, here are the steps:

  1. Create an MVC 3 application.
  2. Create Model classes.
  3. Scaffold the controllers and views.
  4. Add the connection string to Web.Config
  5. Adjust Global.asax Application Start 

Connection String

 

    <add
    name="WithCompactContext"
    connectionString="DataSource=|DataDirectory|MyDb.sdf"
    providerName="System.Data.SqlServerCe.4.0"/>

 

Global.asax::Application_Start

            System.Data.Entity.Database.SetInitializer(
                new System.Data.Entity.DropCreateDatabaseIfModelChanges<WithCompact.Models.WithCompactContext>());

This option tells the EF to recreate the database if model changes. Tip: make sure you don't already have the database file created when working with SQL Server Compact, otherwise the following errors pops up

Model compatibility cannot be checked because the database does not contain model metadata. Ensure that IncludeMetadataConvention has been added to the DbModelBuilder conventions.

 

No comments: