Generate SQL CE database from EF Code-First DbContext class

Bent Rasmussen picture Bent Rasmussen · Jan 29, 2011 · Viewed 14.1k times · Source

I've defined a set of classes in the style of Entity Framework Code-First conventions and annotated the class properties with System.ComponentModel.DataAnnotations attributes.

Now I want to generate a SQL Server Compact Edition (SCSE) (4.0) database from this code.

What code is needed to do this and what assemblies need to be imported?

So far I've imported the C:\Program Files (x86)\Microsoft SQL Server Compact Edition\v4.0\Desktop{System.Data.SqlServerCe.dll,System.Data.SqlServerCe.Entity\System.Data.SqlServerCe.Entity.dll} dll files.

Any pointers appreciated. Articles and whatnot.

Answer

Bent Rasmussen picture Bent Rasmussen · Jan 31, 2011

I found the solution. The critical thing is this line of code:

DbDatabase.DefaultConnectionFactory = new 
                      SqlCeConnectionFactory("System.Data.SqlServerCe.4.0");

Here's a full sample:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace Proto
{
    using System.Data;
    using System.Data.Entity;
    using System.Data.Entity.Database;
    using System.Data.SqlServerCe;
    using System.ComponentModel.DataAnnotations;

    class Program
    {
        static void Main(string[] args)
        {
            DbDatabase.DefaultConnectionFactory = new 
                        SqlCeConnectionFactory("System.Data.SqlServerCe.4.0");
            DbDatabase.SetInitializer(
                         new DropCreateDatabaseIfModelChanges<ProtoCatalog>()
                  );

            using (var db = new ProtoCatalog())
            {
                var user = new User
                {
                    Name = "bob",
                    Password = "123",
                    Creation = DateTime.Now,
                    PrimaryEmailAddress = "[email protected]"
                };

                db.Users.Add(user);

                db.SaveChanges();

                Console.ReadKey();
            }
       }
    }

    public class ProtoCatalog : DbContext
    {
        public DbSet<User> Users { get; set; }
    }

    public class User
    {
        [Key, StringLength(50)]
        public string Name { get; set; }

        [Required, StringLength(100)]
        public string Password { get; set; }

        [Required, StringLength(320)]
        public string PrimaryEmailAddress { get; set; }

        [StringLength(320)]
        public string SecondaryEmailAddress { get; set; }

        [Required]
        public DateTime Creation { get; set; }

        public bool Active { get; set; }
    }
}

The API will probably change between EF Code-First CTP 5 and RTM though, but this is how it's done now.

I've made a small blog post about it.