SQL CE and namespaces

We use SQL CE in our unit test project to test our EF6 queries. This works pretty well and Code first setup makes sure each test gets a fresh CE database to work with.

We ran into a problem where two EF types had the same table name but inside different schemas. CE does not support schemas and this resulted in naming conflicts when setting up database. My solution was to create a little convention.

public class BakeSchemaIntoTableNameConvention : IStoreModelConvention<EntityType>
{
    public void Apply(EntityType item, DbModel model)
    {
        var entitySet = model.StoreModel.Container.EntitySets.Single(es => es.ElementType == item);
        entitySet.Table = $"{entitySet.Schema}_{entitySet.Table}";
    }
}

It bakes the schema into the table name like dbo_MyTable. You add the convention like.

protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
    modelBuilder.Conventions.Add<BakeSchemaIntoTableNameConvention>();

    modelBuilder.Configurations.AddFromAssembly(typeof (MyContext).Assembly);
}

You do not want to add this for production code so what I did was create a public event on the context. And call it from the OnModelCreating method.

protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
    ModelCreating?.Invoke(this, modelBuilder);

    modelBuilder.Configurations.AddFromAssembly(typeof (MyContext).Assembly);
}

Call it from your Unittest project like.

ctx.ModelCreating += (s, e) => e.Conventions.Add<BakeSchemaIntoTableNameConvention>();
Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s