Friday, April 30, 2010

How to switch between SQL Server and SQL Server Compact with Entity Framework

I wanted to be able to save data to either a database on a SQL Server 2008 or an equivalent database on SQL Server Compact 3.5 with the minimum of hassle. Enter the new features of Entity Framework 4.0. I followed POCO in the Entity Framework: Part 1 - The Experience to turn off code generation.

I added two EDMs to my project, one for each database. I modified the ObjectContext class to accept different contexts, i.e.:

public class TestContext : ObjectContext
public TestContext(string contextName) : base("name=" + contextName, contextName)
_projects = CreateObjectSet<Project>();

public ObjectSet<Project> Projects
return _projects;
private ObjectSet<Project> _projects;

After that, I can now connect to either database by specifying either:

var compactContext = new TestContext("CompactEntities");


var context = new TestContext("Entities");

Now I can use the same class files to both databases, and sync up the data in both with quite easily. The only redundancy is the EDMs, but since they are generated by Visual Studio, I don't care.

All too easy.

No comments:

Post a Comment