Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
603 views
in Technique[技术] by (71.8m points)

.net - How to change LINQ O/R-M table name/source during runtime?

I've got a database, and an entityset created by the O/R-Mapper, using all this with LINQ.

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

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

Now I'd like to change this table name during runtime, so the SQL will be run against some other table (customers2008 instead of customer, for example).

Is there any way to change the table name (source name) during runtime?

[Update] After some testing to my dismay I had to discover that XmlMappingSource does render computed properties which are not persisted in the database unaccessable (yes, even the mapping created by SqlMetal does ignore everything which is not persisted).

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Kind of ... You'd have to do something like this:

  1. Create the entities in the designer.
  2. Use SqlMetal to generate an xml mapping file from the .dbml file generate by the designer.
  3. Update the table names in the xml file.
  4. Then in your code, use the DataContext constructor overload that accepts an XmlMappingSource created with 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'm using a similar process with an ERP database that has table names like ttccom001xxx where xxx is the installation ID (I know it's a horrible schema, but there's nothing I can do about it). We have multiple installations, so I copy the initial xml mapping once for each installation and then replace xxx with the installation ID. I wrote a small console app that uses Regex to take care the replacements and added it as part of my build process.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...