实体框架代码首先和继承
假设我有一组现有的数据库表如下。
1. Medication_Orders
2. Lab_And_Radiology_Orders
3. Immunization_Orders
您可以看到这些表与订单的概念有关。每个表都有自己的实体数据,但Lab_And_Radiology除外,它包含两种不同类型的订单。他们有一个名为Order_Type的鉴别器列,介于Lab和Radiology订单之间。
在Code First中,我将我的类层次结构定义如下。
Suppose I have an existing set of database tables as following.
1. Medication_Orders
2. Lab_And_Radiology_Orders
3. Immunization_Orders
You can see that these tables relates to a concept of "Orders". Each table its own entity data except Lab_And_Radiology which holds two distinct type of Orders. They have a discriminator column called Order_Type to different between between Lab and Radiology orders.
In Code First, I defined my class hierarchy as following.
<pre lang="c#">
公共抽象类订单{//基类属性}
公共类LabOrder:订单{//填写上面的表#2,其中order_type ='L'}
公共类RadiologyOrder :订单{//填写上面的表#2,其中订单类型='R'}
公共类MedicationOrder:订单{//填充上面的表#1。 }
公共类ImmunizationOrder:订单{//填充上面的表#3。}
我'无法在EF代码中配置第一个流畅的API。你可以看到我的桌子同时有TPH和TPC场景。
我尝试了什么:
我试图在我的示例应用程序中实现它但无法使其正常工作。
public abstract class Order { //base class properties }
public class LabOrder:Order { //populates from table # 2 above where order_type = 'L' }
public class RadiologyOrder:Order { //populates from table # 2 above where order type='R'}
public class MedicationOrder:Order {//populates from table# 1 above.}
public class ImmunizationOrder:Order { //populates from table# 3 above.}
I'm not able to configure this in E.F code first fluent API. As you can see my tables have both TPH and TPC scenarios.
What I have tried:
I have tried to implement this in my sample app but unable to make it work.
首先,您没有向我们展示您的DbContext和你的配置,所以几乎不可能告诉你哪里出错了。但是,通过你发布的内容,我认为你的内容过于复杂。
接下来,所有这些类型最终会出现在同一个表中,Orders。您的实验室和放射学报告的鉴别器是多余的。
First you haven't shown us your DbContext and your configuration, so it's pretty much impossible to tell you where you went wrong. But, by what you have posted, i think you're over-complicating things.
Next, all of these types will end up in the same table, Orders. Your discriminator for Lab and Radiology reports is redundant.
public abstract class Order
public class LabOrder : Order
public class MedicationOrder : Order
public class ImmunizationOrder : Order
DbContext:
DbContext:
public class MyDbContext : DbContext
{
public DbSet<Order> Orders { get; set; }
}
就是这样!对于基本的每层次表继承图,不需要做任何事情。
如果这是你第一次进入实体框架,我强烈建议你拿一本书在你潜入之前你还是两个。你不会从一堆论坛帖子中学习EF所使用的所有内容和惯例。
That's it! Nothing else needs to be done for a basic table-per-hierarchy inheritance graph.
If this is your first foray into Entity Framework, I HIGHLY suggest you pickup a book or two on it before you dive in. You're not going to learn all of the in's and out's and conventions that EF uses from a bunch of forum posts.