Entity Framework with Dynamic Table Mapping Based on a Parameter (PostgreSQL Partitioning)

Florin 0 Reputation points
2025-01-31T08:50:51.2966667+00:00

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:

  1. How can I make Entity Framework dynamically map my model to the correct table based on the company?
  2. Is there a way to handle this efficiently without manually updating the DbContext for every new company?
  3. 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?

Entity Framework Core
Entity Framework Core
A lightweight, extensible, open-source, and cross-platform version of the Entity Framework data access technology.
777 questions
C#
C#
An object-oriented and type-safe programming language that has its roots in the C family of languages and includes support for component-oriented programming.
11,260 questions
0 comments No comments
{count} votes

Your answer

Answers can be marked as Accepted Answers by the question author, which helps users to know the answer solved the author's problem.