【问题标题】:How to model collection of mixed entities using EF code first如何首先使用 EF 代码对混合实体的集合进行建模
【发布时间】:2013-02-14 13:50:23
【问题描述】:

我在 VS2010 中使用 EF5。 我有两种类型的工作样本:人员,业务 我想添加一个类似的集合

DbSet<Customer> Customers

Customers 中的对象可以是 Person 或 Business。在我的应用中,我希望能够执行以下操作:

mycontext.Customers.Add(new Person());
mycontext.Customers.Add(new Business());

我认为客户表可能看起来像

id (id of Person or Business)
discriminator

如何通过代码优先实现?

【问题讨论】:

    标签: c# ef-code-first entity-framework-5


    【解决方案1】:

    使用 ID 属性创建基类 Customers 并从 Customers 派生 PersonBusiness

    【讨论】:

    • 或者接口取决于Person和Business是否共享逻辑
    • 我完全同意。但尚未从 OP 的问题中看出。
    • person 和 Business 类已经实现为完全独立的,并且在不同的表中。他们唯一的共同点是两者都可以成为客户。
    • 这完全没问题,这并不重要...您现在只需创建一个新类。这个新班级你叫Customer。在该新类中,您创建一个名称为:Id 的属性。完成后,您可以从 Customer 派生 Person 和 Business,如下所示:public class Person : Customer { } 现在您可以同时使用 Customer:mycontext.Customers.Add(new Person());mycontext.Customers.Add(new Business());
    • 这只会将 Person 和 Business 放在一个表中。 Person 和 Business 已经在它们自己的表中。我需要 Customer 在单独的表中。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-04-07
    • 2020-06-30
    • 1970-01-01
    • 2016-01-09
    相关资源
    最近更新 更多