Entity Framework database-first - dynamically adding table to model

c# ef-database-first entity-framework-6


I have tables with the same structure but with a letter prefix of every table.

For example:

A_Company, B_Company, C_Company

There is combo box from which the user can select A, B or C, and then the code saves data into the appropriate table.

How can I do this using EF database-first?

12/10/2017 3:07:24 PM

Accepted Answer

I solved this problem adding a column for code prefix and triggers on my base table company for insert update and delete.

1/27/2018 1:25:14 PM

Popular Answer

As the other commenters have said, it would be much better to refactor the database to a single table. If you can't do that then the only other thing that I can think of is to have a class which will select the table for you.

I would create a new class which has the same properties as your company tables, and also has the descriminator property. This would then be used as the data source for your ui.

in this class you would have to code manually to draw the data from the correct actual table (and save to it) based on the value of the discriminator. This is fine if you have only a few tables, but as your number of identical tables grows large, this will become more of a headache.

It might be possible to have the base tables all inherit from a virtual base class which would help a bit - you could then create a dictionary which the base class could use to switch the final data source on the fly.

As a final thought have you considered: 1. Creating the master table as suggested by the other commentators as a single table and then having views for each company.

  1. Creating the master table as suggested and then having code to create the individual tables from that one at some point prior to their use?

Related Questions


Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow