Entity Framework with Dynamic Table Mapping Based on a Parameter (PostgreSQL Partitioning)
I am using Entity Framework with PostgreSQL and need a way to dynamically map a model to different tables based on a parameter.
For example, I have a Cars model, and each company should have its own separate table:
-
Cars_A
for Company A -
Cars_B
for Company B -
Cars_C
for Company C (created dynamically when a new company registers)
Each company should only see its own cars. New companies are added every week, so I cannot create separate models for each company. Instead, I need a single model that dynamically maps to the corresponding table (Masini_X
) at runtime.
My questions are:
- How can I make Entity Framework dynamically map my model to the correct table based on the company?
- Is there a way to handle this efficiently without manually updating the DbContext for every new company?
- Would PostgreSQL partitioning be a good approach for this use case, or is there a better alternative?
The main reason for this approach is performance and data isolation, as a single table would be too large to manage efficiently. Any suggestions or alternative solutions would be greatly appreciated!
[Edit]
I have found two potentially more efficient solutions:
1. Using Dapper – Since Dapper is a micro-ORM, it allows for direct SQL queries, making it easier to dynamically route queries to different tables without the constraints of Entity Framework.
2. Keeping a single large table and using Redis for caching – Instead of splitting tables, I could store each company’s cars in a separate Redis hash, significantly reducing database queries and improving performance.
Would these approaches be more scalable in the long run? Any insights or potential drawbacks?