Entity Framework using Poco and custom Sql Database Schema<!-- --> | <!-- -->Patrick Desjardins Blog
Patrick Desjardins Blog
Patrick Desjardins picture from a conference

Entity Framework using Poco and custom Sql Database Schema

Posted on: March 16, 2012

First of all, the code in this post is not all of mine. I do not remember the source and if anyone know please let me know I will acknowledge the creator.

Entity Framework use the default schema when accessing the database. It uses the "dbo" one usually.

You may need to use Entity Framework with different schema. This can be done by overriding the creation of the model that is done with the method "OnModelCreating". This can be done inside your custom DbObject class.

1public string DefaultSchema { get; set; }
2protected override void OnModelCreating(DbModelBuilder modelBuilder) {
3 if (!String.IsNullOrEmpty(DefaultSchema)) {
4 var entityMethod = modelBuilder.GetType().GetMethod("Entity");
5 foreach (PropertyInfo dbSet in GetType().GetProperties().Where(t =>t.PropertyType.IsGenericType && t.PropertyType.GetGenericTypeDefinition().Equals(typeof (DbSet<>)))) {
6 var entityType = dbSet.PropertyType.GetGenericArguments();
7 var entityMethodGeneric = entityMethod.MakeGenericMethod(entityType);
8 var entityConfig = entityMethodGeneric.Invoke(modelBuilder, null);
9 var toTableMethod = entityConfig.GetType().GetMethod("ToTable", new[]{typeof (string), typeof (string)});
10 var tableName = GetTableName(entityType.FirstOrDefault());
11 toTableMethod.Invoke(entityConfig, new object[]{tableName, DefaultSchema});
12 }
14 }
16 base.OnModelCreating(modelBuilder);
19private string GetTableName(Type type) {
20 var tableAttribute = type.GetCustomAttributes(false).OfType<System.ComponentModel.DataAnnotations.TableAttribute>().FirstOrDefault();
21 return tableAttribute == null ? type.Name : tableAttribute.Name;

With the code above, you can set the DefaultSchema and the query will be made with the schema desired.

This is the reference of the Schema code : http://social.msdn.microsoft.com/Forums/en-US/adodotnetentityframework/thread/e276fb02-ef9b-44eb-b481-699c1c25602d/