简体   繁体   中英

Entity Framework Core - Creating a dynamic DbSet Model from TableName

Let's say we have a few clients, and each client has a Database with a "Employees" table, but for each client the table is a little different. Most of the columns are the same, but there are a few clients with more/less columns for that table.

I currently have an "Employee" class that represents the basic table, which is used in my DbContext in the DbSet. Eventually I would like to just make some CRUD operations on that table.

Using EFCore, I'm having some trouble writing a generic code, that will work for all clients, regardless of how many columns they have for that table. (The tableName stays the same for all clients)

Any ideas on how to solve this? Maybe creating the Entity dynamically? Or extending the current "Employee" class?

There are 3 common ways to implement inheritance

  • Table Per Hierarchy (TPH)
  • Table Per Type (TPT)
  • Table Per Concrete Type (TPC)

In EF core only the first one is applicable. Additionally, you can specify a name and data type for the discriminator column and the values to represent each type. In case you use fluent config it would be:

modelBuilder.Entity<Employee>()
    .ToTable("Employee")
    .HasDiscriminator<int>("EmployeeType")
    .HasValue<Vanilla>(1)
    .HasValue<Customer1>(2)
    .HasValue<Customer2>(3);

This would store all values in one table and Costumer1 specific values would be nulls if it is not Customer1. I made the vanilla as you said "more/less columns" and Employee would be true base class common for all.

Additionally, here is an example how to set up table per hierarchy .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM