I have to write a C# application that works with a SQL server database created and mantained by an old application. The application creates new tables each year and the “year property” is in the table name. The number of tables it creates may vary depending of the number of “sections” that the user has created inside the application. So, I have to work with tables like Cwx_DRyz (quite self explanatory…), where “wx” can be the section, and “yz” would be the year. An example of group of table could be:
C01_DR07
C01_DR08
C01_DR09
C02_DR08
C02_DR09
C03_DR06
C04_DR12
And all of those tables could represent, for example, clients. They would be clients from different sections and years, but clients with the same structure.
My question is: Can I have a Client entity to handle all those tables and change the mapping from one to another at runtime? The title says “unknown” because I don’t know the tables before runtime.
The most similar question I have found is Entity Framework map multiple tables to one entity and the answer is to use the “Table Per Concrete Type Inheritance”, but it is not useful for my case.
PS: EF version 4.3.1 and VS2010
EDIT: The tables don’t have primary keys… Most of them have columns that are supossed to have unique values (integer or string).
If you use “code first” you could create a mapping as you want. This also works with existing databases when the mapping you have created match the database.
So whenever you create a context you can build the string (tablename) you want to map to.
Some codesamples for “code first” and how you could start:
The DbContext:
GeneralEntitiesConfiguration is a class im using to handle the configurations, nothing more than a helper which looks like:
YourEntityConfiguration is a class where i have all the configurations for this entity:
At the application startup (or before you initialize your context the first time) you have to initialize the database. Therefore you can use an initializer which checks the database and handles differences. Build in there are things like “DropCreateDatabaseAlways” or “DropCreateDatabaseIfModelChanges” => you would need to create your own which just ignores any differences. In my sample i have create one which just throws an exception when the model differs (i wanted to handle model changes with scipts for the first try):
Hope you have got an idea of you can handle dynamic table names with entity framework!
If there are more questions just ask 😉