Sign Up

Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.

Have an account? Sign In

Have an account? Sign In Now

Sign In

Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.

Sign Up Here

Forgot Password?

Don't have account, Sign Up Here

Forgot Password

Lost your password? Please enter your email address. You will receive a link and will create a new password via email.

Have an account? Sign In Now

You must login to ask a question.

Forgot Password?

Need An Account, Sign Up Here

Please briefly explain why you feel this question should be reported.

Please briefly explain why you feel this answer should be reported.

Please briefly explain why you feel this user should be reported.

Sign InSign Up

The Archive Base

The Archive Base Logo The Archive Base Logo

The Archive Base Navigation

  • SEARCH
  • Home
  • About Us
  • Blog
  • Contact Us
Search
Ask A Question

Mobile menu

Close
Ask a Question
  • Home
  • Add group
  • Groups page
  • Feed
  • User Profile
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Buy Points
  • Users
  • Help
  • Buy Theme
  • SEARCH
Home/ Questions/Q 775957
In Process

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: May 14, 20262026-05-14T19:22:27+00:00 2026-05-14T19:22:27+00:00

I wish to be able to change the table a class is mapped to

  • 0

I wish to be able to change the table a class is mapped to at run time, I can’t do this if all the mappings are defined with attributes. Therefore is there a way to define the mappings at runtime in code.

(I would rather not have to maintain xml mapping files.)


Say I have two tables:

  • OldData
  • NewData

and sometimes I wished to query OldData and other times I wished to query NewData. I want to use the same code to build the queries in both cases.


See also “How to map an Entity framework model to a table name dynamically“

  • 1 1 Answer
  • 0 Views
  • 0 Followers
  • 0
Share
  • Facebook
  • Report

Leave an answer
Cancel reply

You must login to add an answer.

Forgot Password?

Need An Account, Sign Up Here

1 Answer

  • Voted
  • Oldest
  • Recent
  • Random
  1. Editorial Team
    Editorial Team
    2026-05-14T19:22:28+00:00Added an answer on May 14, 2026 at 7:22 pm

    In order to make this truly transparent, you have to jump through some pretty crazy hoops, but it can be done by overriding all the Meta*** classes with your own derived types.

    This would actually be fairly straightforward with a proxy/method interception library like Castle, but assuming the lowest common denominator here, it’s basically a long and boring ordeal of implementing every single meta method to wrap the original type, because you can’t derive directly from any of the attribute mapping classes.

    I’ll try to stick to the important overrides here; if you don’t see a particular method/property in the code below, it means that the implementation is literally a one-liner that wraps the “inner” method/property and returns the result. I’ve posted the whole thing, one-line methods and all, on PasteBin so you can cut/paste for testing/experimentation.

    The first thing you need is a quick override declaration, which looks like this:

    class TableOverride
    {
        public TableOverride(Type entityType, string tableName)
        {
            if (entityType == null)
                throw new ArgumentNullException("entityType");
            if (string.IsNullOrEmpty(tableName))
                throw new ArgumentNullException("tableName");
            this.EntityType = entityType;
            this.TableName = tableName;
        }
    
        public Type EntityType { get; private set; }
        public string TableName { get; private set; }
    }
    

    Now the meta classes. Starting from the lowest level, you have to implement a MetaType wrapper:

    class OverrideMetaType : MetaType
    {
        private readonly MetaModel model;
        private readonly MetaType innerType;
        private readonly MetaTable overrideTable;
    
        public OverrideMetaType(MetaModel model, MetaType innerType,
            MetaTable overrideTable)
        {
            if (model == null)
                throw new ArgumentNullException("model");
            if (innerType == null)
                throw new ArgumentNullException("innerType");
            if (overrideTable == null)
                throw new ArgumentNullException("overrideTable");
            this.model = model;
            this.innerType = innerType;
            this.overrideTable = overrideTable;
        }
    
        public override MetaModel Model
        {
            get { return model; }
        }
    
        public override MetaTable Table
        {
            get { return overrideTable; }
        }
    }
    

    Again, you have to implement about 30 properties/methods for this, I’ve excluded the ones that just return innerType.XYZ. Still with me? OK, next is the MetaTable:

    class OverrideMetaTable : MetaTable
    {
        private readonly MetaModel model;
        private readonly MetaTable innerTable;
        private readonly string tableName;
    
        public OverrideMetaTable(MetaModel model, MetaTable innerTable,
            string tableName)
        {
            if (model == null)
                throw new ArgumentNullException("model");
            if (innerTable == null)
                throw new ArgumentNullException("innerTable");
            if (string.IsNullOrEmpty(tableName))
                throw new ArgumentNullException("tableName");
            this.model = model;
            this.innerTable = innerTable;
            this.tableName = tableName;
        }
    
        public override MetaModel Model
        {
            get { return model; }
        }
    
        public override MetaType RowType
        {
            get { return new OverrideMetaType(model, innerTable.RowType, this); }
        }
    
        public override string TableName
        {
            get { return tableName; }
        }
    }
    

    Yup, boring. OK, next is the MetaModel itself. Here things get a little more interesting, this is where we really start declaring overrides:

    class OverrideMetaModel : MetaModel
    {
        private readonly MappingSource source;
        private readonly MetaModel innerModel;
        private readonly List<TableOverride> tableOverrides = new 
            List<TableOverride>();
    
        public OverrideMetaModel(MappingSource source, MetaModel innerModel,
            IEnumerable<TableOverride> tableOverrides)
        {
            if (source == null)
                throw new ArgumentNullException("source");
            if (innerModel == null)
                throw new ArgumentNullException("innerModel");
            this.source = source;
            this.innerModel = innerModel;
            if (tableOverrides != null)
                this.tableOverrides.AddRange(tableOverrides);
        }
    
        public override Type ContextType
        {
            get { return innerModel.ContextType; }
        }
    
        public override string DatabaseName
        {
            get { return innerModel.DatabaseName; }
        }
    
        public override MetaFunction GetFunction(MethodInfo method)
        {
            return innerModel.GetFunction(method);
        }
    
        public override IEnumerable<MetaFunction> GetFunctions()
        {
            return innerModel.GetFunctions();
        }
    
        public override MetaType GetMetaType(Type type)
        {
            return Wrap(innerModel.GetMetaType(type));
        }
    
        public override MetaTable GetTable(Type rowType)
        {
            return Wrap(innerModel.GetTable(rowType));
        }
    
        public override IEnumerable<MetaTable> GetTables()
        {
            return innerModel.GetTables().Select(t => Wrap(t));
        }
    
        private MetaTable Wrap(MetaTable innerTable)
        {
            TableOverride ovr = tableOverrides.FirstOrDefault(o => 
                o.EntityType == innerTable.RowType.Type);
            return (ovr != null) ?
                new OverrideMetaTable(this, innerTable, ovr.TableName) : 
                innerTable;
        }
    
        private MetaType Wrap(MetaType innerType)
        {
            TableOverride ovr = tableOverrides.FirstOrDefault(o =>
                o.EntityType == innerType.Type);
            return (ovr != null) ?
                new OverrideMetaType(this, innerType, Wrap(innerType.Table)) :
                innerType;
        }
    
        public override MappingSource MappingSource
        {
            get { return source; }
        }
    }
    

    We’re almost done! Now you just need the mapping source:

    class OverrideMappingSource : MappingSource
    {
        private readonly MappingSource innerSource;
        private readonly List<TableOverride> tableOverrides = new
            List<TableOverride>();
    
        public OverrideMappingSource(MappingSource innerSource)
        {
            if (innerSource == null)
                throw new ArgumentNullException("innerSource");
            this.innerSource = innerSource;
        }
    
        protected override MetaModel CreateModel(Type dataContextType)
        {
            var innerModel = innerSource.GetModel(dataContextType);
            return new OverrideMetaModel(this, innerModel, tableOverrides);
        }
    
        public void OverrideTable(Type entityType, string tableName)
        {
            tableOverrides.Add(new TableOverride(entityType, tableName));
        }
    }
    

    Now we can FINALLY start using this (phew):

    var realSource = new AttributeMappingSource();
    var overrideSource = new OverrideMappingSource(realSource);
    overrideSource.OverrideTable(typeof(Customer), "NewCustomer");
    string connection = Properties.Settings.Default.MyConnectionString;
    using (MyDataContext context = new MyDataContext(connection, overrideSource))
    {
        // Do your work here
    }
    

    I’ve tested this with queries and also with insertions (InsertOnSubmit). It’s possible, actually rather likely, that I’ve missed something in my very basic testing. Oh, and this will only work if the two tables are literally exactly the same, column names and all.

    It will probably mess up if this table has any associations (foreign keys), since you’d have to override the association names too, on both ends. I’ll leave that as an exercise to the reader, since thinking about it makes my head hurt. You’d probably be better off just removing any associations from this particular table, so you don’t have to deal with that headache.

    Have fun!

    • 0
    • Reply
    • Share
      Share
      • Share on Facebook
      • Share on Twitter
      • Share on LinkedIn
      • Share on WhatsApp
      • Report

Sidebar

Related Questions

As the topic suggests I wish to be able to pass table names as
I have a 3d object that I wish to be able to rotate around
I wish to know all the pros and cons about using these two methods.
I wish to implement a 2d bit map class in Python. The class would
I wish I were a CSS smarty .... How can you place a div
I wish to search a database table on a nullable column. Sometimes the value
I wish Subversion had a better way of moving tags. The only way that
I wish to implement my software on a shareware basis, so that the user
I wish to use xml and xsl to generate controls on an asp.net page.
I wish to test a function that will generate lorem ipsum text, but it

Explore

  • Home
  • Add group
  • Groups page
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Users
  • Help
  • SEARCH

Footer

© 2021 The Archive Base. All Rights Reserved
With Love by The Archive Base

Insert/edit link

Enter the destination URL

Or link to existing content

    No search term specified. Showing recent items. Search or use up and down arrow keys to select an item.