none
Change Table Mapping at Runtime RRS feed

  • Question

  • Hi There,

    When using the entity framework and generating a map from a database, is it possible to change the name of a table that an entity is mapped to at runtime?

    I have read that it is possible to do this when developing with the code-first model and inheriting from DbContext and overriding the OnModelCreating method, however when generating from a Database, the model inherits from ObjectContext, which has no such override-able method.  I realise that DbContext is a wrapper of ObjectContext, however does anyone know if there is a way of achieving this through the ObjectContext object, rather than going in and forcing the automatically created designer to inherit from DbContext etc, as I don't really want to mess around with that.

    I have google this quite a lot but end up following references that all seem to lead to the DbContext class, not the ObjectContext class.  Any help would be much appreciated!

    Friday, August 16, 2013 10:56 AM

Answers

  • Hi GreatUncleBulgaria,

    Thanks for your post!

    As far as I know, we can use DbModelBuilder Class to achieve that. DbModelBuilder is used to map CLR classes to a database schema. This code centric approach to building an Entity Data Model (EDM) model is known as Code First.

    I tried a simple example below:

    Models:

    public class AppModel
        {
            public int Id { get; set; }
    
    }
    public class Country : AppModel
        {
            public string Name { get; set; }
    
    }
    public class CountryLanguage:AppModel
        {
            public Language Language { get; set; }
            public Country Country { get; set; }
    
    }
    public class Language : AppModel
        {
            public string Name { get; set; }
    
     }
    

    Persistence:

    public class PersistenceContext : ObjectContext
        {
            private readonly Dictionary<Type, object> _dbSets = new Dictionary<Type, object>();
    
            public PersistenceContext(EntityConnection connection):base(connection)
            {
    
            }
    
            private IObjectSet<T> GetDbSet<T>() where T : AppModel
            {
                if (!_dbSets.ContainsKey(typeof(T)))
                {
                    _dbSets[typeof(T)] = this.CreateObjectSet<T>();
                }
    
                return _dbSets[typeof(T)] as IObjectSet<T>;
            }
    
            public IObjectSet<Country> Countries
            {
                get { return GetDbSet<Country>(); }
            }
    
            public IObjectSet<Language> Languages
            {
                get { return GetDbSet<Language>(); }
            }
    
            public IObjectSet<CountryLanguage> CountryLanguages
            {
                get { return GetDbSet<CountryLanguage>(); }
            }
    }
    

    Utils:

    public class AppConfig
        {
            public static DbModelBuilder GetBuilder()
            {
                DbModelBuilder builder = new DbModelBuilder();
                builder.Entity<EdmMetadata>().ToTable("EdmMetadata");
    
                builder.Entity<Language>().ToTable("LanguageT");
                builder.Entity<Country>().ToTable("CountryT");
                builder.Entity<CountryLanguage>().ToTable("CountryLanguageT");
    
                return builder;
            }
    
    }
    

    Program:

    class Program
        {
            static void Main(string[] args)
            {
                var connectionString = @"Data Source=(localdb)\v11.0;Initial Catalog=TestDb2;Integrated Security=True";
                DbModelBuilder builder = AppConfig.GetBuilder();
                DbConnection connection = new SqlConnection(connectionString);
                DbCompiledModel model = builder.Build(connection).Compile();
    
                PersistenceContext context = model.CreateObjectContext<PersistenceContext>(connection);
    
                var temp1 = context.Languages.ToList();
                var temp2 = context.Countries.ToList();
                var temp3 = context.CountryLanguages.ToList();
    
                context.Dispose();
                connection.Dispose();
    
            }
       }
    

    Here are some references below that may benefit to you:

    DbModelBuilder Class:

    http://msdn.microsoft.com/en-us/library/system.data.entity.dbmodelbuilder(v=vs.103).aspx

    Code First:

    http://blogs.msdn.com/b/adonet/archive/2010/07/14/ctp4codefirstwalkthrough.aspx

    Thanks

    Best Regards


    <THE CONTENT IS PROVIDED "AS IS" WITHOUT WARRANTY OF ANY KIND, WHETHER EXPRESS OR IMPLIED>
    Thanks
    MSDN Community Support

    Please remember to "Mark as Answer" the responses that resolved your issue. It is a common way to recognize those who have helped you, and makes it easier for other visitors to find the resolution later.

    Monday, August 19, 2013 9:43 AM
    Moderator

All replies

  • Hi GreatUncleBulgaria,

    Thanks for your post!

    As far as I know, we can use DbModelBuilder Class to achieve that. DbModelBuilder is used to map CLR classes to a database schema. This code centric approach to building an Entity Data Model (EDM) model is known as Code First.

    I tried a simple example below:

    Models:

    public class AppModel
        {
            public int Id { get; set; }
    
    }
    public class Country : AppModel
        {
            public string Name { get; set; }
    
    }
    public class CountryLanguage:AppModel
        {
            public Language Language { get; set; }
            public Country Country { get; set; }
    
    }
    public class Language : AppModel
        {
            public string Name { get; set; }
    
     }
    

    Persistence:

    public class PersistenceContext : ObjectContext
        {
            private readonly Dictionary<Type, object> _dbSets = new Dictionary<Type, object>();
    
            public PersistenceContext(EntityConnection connection):base(connection)
            {
    
            }
    
            private IObjectSet<T> GetDbSet<T>() where T : AppModel
            {
                if (!_dbSets.ContainsKey(typeof(T)))
                {
                    _dbSets[typeof(T)] = this.CreateObjectSet<T>();
                }
    
                return _dbSets[typeof(T)] as IObjectSet<T>;
            }
    
            public IObjectSet<Country> Countries
            {
                get { return GetDbSet<Country>(); }
            }
    
            public IObjectSet<Language> Languages
            {
                get { return GetDbSet<Language>(); }
            }
    
            public IObjectSet<CountryLanguage> CountryLanguages
            {
                get { return GetDbSet<CountryLanguage>(); }
            }
    }
    

    Utils:

    public class AppConfig
        {
            public static DbModelBuilder GetBuilder()
            {
                DbModelBuilder builder = new DbModelBuilder();
                builder.Entity<EdmMetadata>().ToTable("EdmMetadata");
    
                builder.Entity<Language>().ToTable("LanguageT");
                builder.Entity<Country>().ToTable("CountryT");
                builder.Entity<CountryLanguage>().ToTable("CountryLanguageT");
    
                return builder;
            }
    
    }
    

    Program:

    class Program
        {
            static void Main(string[] args)
            {
                var connectionString = @"Data Source=(localdb)\v11.0;Initial Catalog=TestDb2;Integrated Security=True";
                DbModelBuilder builder = AppConfig.GetBuilder();
                DbConnection connection = new SqlConnection(connectionString);
                DbCompiledModel model = builder.Build(connection).Compile();
    
                PersistenceContext context = model.CreateObjectContext<PersistenceContext>(connection);
    
                var temp1 = context.Languages.ToList();
                var temp2 = context.Countries.ToList();
                var temp3 = context.CountryLanguages.ToList();
    
                context.Dispose();
                connection.Dispose();
    
            }
       }
    

    Here are some references below that may benefit to you:

    DbModelBuilder Class:

    http://msdn.microsoft.com/en-us/library/system.data.entity.dbmodelbuilder(v=vs.103).aspx

    Code First:

    http://blogs.msdn.com/b/adonet/archive/2010/07/14/ctp4codefirstwalkthrough.aspx

    Thanks

    Best Regards


    <THE CONTENT IS PROVIDED "AS IS" WITHOUT WARRANTY OF ANY KIND, WHETHER EXPRESS OR IMPLIED>
    Thanks
    MSDN Community Support

    Please remember to "Mark as Answer" the responses that resolved your issue. It is a common way to recognize those who have helped you, and makes it easier for other visitors to find the resolution later.

    Monday, August 19, 2013 9:43 AM
    Moderator
  • Thanks for the advice Starain, I will look into this.
    Monday, August 19, 2013 10:16 AM