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.
There is no way to convert your code-first classes into database-first classes. Creating the model from the database will create a whole new set of classes, regardless of the presence of your code-first classes. However, you might not want to delete your code-first classes right away.
To use code-first for an existing database, right click on your project in Visual Studio -> Add -> New Item.. Select ADO.NET Entity Data Model in the Add New Item dialog box and specify the model name (this will be a context class name) and click on Add. This will open the Entity Data Model wizard as shown below.
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.
See this blog and links in the same (for example the ScottGu article): http://erikej.blogspot.com/2011/01/sql-server-compact-40-released.html
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With