Last active
December 19, 2015 03:08
-
-
Save tracker1/5887849 to your computer and use it in GitHub Desktop.
Create an Entity Framework context bound to a model against an empty SQL Compact Edition (SQL CE) database file, for purposes of repository testing.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
using System; | |
using System.Collections.Generic; | |
using System.Configuration; | |
using System.Data.Entity; | |
using System.Data.EntityClient; | |
using System.Data.Metadata.Edm; | |
using System.Data.SqlServerCe; | |
using System.IO; | |
using System.Linq; | |
using System.Reflection; | |
using System.Text; | |
using MyNamespace.Data; | |
namespace MyNamespace.Data.Tests | |
{ | |
public static class TestUtility | |
{ | |
public static MyContext CreateEmptyTestContext() | |
{ | |
//throw new NotImplementedException("Unable to generate a database against SQL Compact with the entities generated with DevArt.Data.Oracle.Entity"); | |
//set to use MyContext.sdf - database in current directory (testing doesn't have an App_Data directory | |
//var dataDir = (new System.IO.FileInfo(typeof(TestUtility).Assembly.Location)).Directory.FullName; | |
string connStr = "Data Source=MyContext.sdf;"; | |
//if there's already a file/instance, delete it | |
if (File.Exists("MyContext.sdf")) File.Delete("MyContext.sdf"); | |
//create an empty database | |
SqlCeEngine engine = new SqlCeEngine(connStr); | |
engine.CreateDatabase(); | |
//get a workspace against the PilotContext data structure | |
var workspace = new MetadataWorkspace(new string[] { "res://*/" }, new Assembly[] { typeof(MyContext).Assembly }); | |
//create an SQL Compact Connection against a local DB for use with testing against these entities. | |
var conn = new SqlCeConnection(connStr); | |
//create an EntityConnection against said workspace and database connection | |
var ec = new EntityConnection(workspace, conn); | |
//create a context instance with the EntityConnection | |
var context = new MyContext(ec); | |
//create database tables | |
context.CreateDatabase(); //throws an exception... problem with oracle based generator against sqlce? | |
//return the MyContext against the Entity model and the temporary database | |
return context; | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Untested against an SQL based Entity model... it should work.. I was trying to use this against a "MyContext" that was created with Devart.Data.Oracle.Entity based models, which didn't work for my use case... throwing this out there in case it can help someone else.