简体   繁体   English

Entity Framework Core - 从 TableName 创建动态 DbSet 模型

[英]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.我目前有一个代表基本表的“员工”类,它在 DbSet 中的 DbContext 中使用。 Eventually I would like to just make some CRUD operations on that table.最终,我只想在该表上进行一些 CRUD 操作。

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.使用 EFCore,我在编写通用代码时遇到了一些麻烦,该代码适用于所有客户端,无论该表有多少列。 (The tableName stays the same for all clients) (所有客户端的 tableName 保持不变)

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有3种常见的方式来实现继承

  • Table Per Hierarchy (TPH)每个层次结构表 (TPH)
  • Table Per Type (TPT)每种类型的表 (TPT)
  • Table Per Concrete Type (TPC)每个混凝土类型的表 (TPC)

In EF core only the first one is applicable.在 EF 核心中,只有第一个适用。 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.这会将所有值存储在一个表中,如果不是 Customer1,则 Costumer1 特定值将为空值。 I made the vanilla as you said "more/less columns" and Employee would be true base class common for all.正如您所说的“更多/更少列”,我制作了香草,而 Employee 将是所有人通用的真正基类。

Additionally, here is an example how to set up table per hierarchy .此外,这里是如何设置每个层次结构表的示例。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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