How to change LINQ O / RM table name / source at runtime?

I have a database and a set of objects created by O / R-Mapper using all this with LINQ.

In O / R-Mapper, I need to enter a table name (source) for each table that is used for SQL generated by LINQ. In the .dbml file, it looks like this:

<Table Name="dbo.Customers" Member="Customers"> 

Now I would like to change this table name at runtime, so that SQL will work against some other table (customers2008 instead of the client, for example).

Is there a way to change the table name (source name) at runtime?

[Update]. After some testing for my disappointment, I had to find that XmlMappingSource renders computed properties that are not stored in the database are not available (yes, even the mapping created by SqlMetal ignores everything that is not saved).

+6
linq linq-to-sql
source share
2 answers

Kind ... You would need to do something like this:

  • Create objects in the constructor.
  • Use SqlMetal to create the xml mapping file from the .dbml file generated by the constructor.
  • Update table names in an XML file.
  • Then in your code, use the overload of the DataContext constructor, which accepts the XmlMappingSource created using the xml mapping file.

Here's a blog post that explains this process step by step: http://weblogs.asp.net/guybarrette/archive/2008/07/23/linq-to-sql-dynamic-mapping.aspx

I use a similar process with an ERP database that has table names like ttccom001xxx, where xxx is the installation identifier (I know this is a terrible scheme, but I can do nothing about it). We have several installations, so I copy the original xml mapping once for each installation, and then replace xxx with the installation identifier. I wrote a small console application that uses Regex to take care of the replacement and added it as part of my build process.

+7
source share

Here is a link to Microsoft Link to an external mapping .

External matching redefines attribute-based mapping.

Here are the highlights.

  • Create an xml that represents your mappings.
  • New XmlMappingSource and assign it your xml.
  • When you create your DataContext, use a constructor that takes an XmlMappingSource, like this one .
+3
source share

All Articles