【问题标题】:Class and Interface hierarchies in Entity Framework?实体框架中的类和接口层次结构?
【发布时间】:2010-09-26 01:55:56
【问题描述】:

我有两个相关的类,它们共享一个公共接口并且都存储在同一个底层数据库表中。但是,Entity Framework 生成一个公共类,我确实需要两个不同的类。我该如何解决这个问题?最好使用基类而不是接口吗?如何更改 EF 模型以提供映射到一张表上的两个类?

编辑: AccountType 属性决定了类的类型;用户或组。

一些简单的代码:

public interface IAccount
{
    string Name { get; set; }
    AccountType AccountType { get; set; }
}

public class GroupAccount : IAccount
{
    public string Name { get; set; }
    public GroupType GroupType { get; set; }
    public AccountType AccountType { get; set; }
}

public class UserAccount : IAccount
{
    public string Username { get; set; }
    public string Password { get; set; }
    public string Name { get; set; }
    public AccountType AccountType { get; set; }
}

【问题讨论】:

    标签: c# entity-framework class-hierarchy


    【解决方案1】:

    这些数据是否有区别?即 AccountType 是否定义了它是哪种类型?如果是这样:

    • EF 应该从存储中创建 Account 实体
    • 然后创建 2 个子类(UserAccount 和 GroupAccount)
    • 在帐户的映射中,指定谓词“添加条件”
      • 将其映射到 AccountType(存储)字段为 1(或其他)的 UserAccount
      • 将其映射到 GroupAccount,其中 AccountType(存储)字段为 2(或其他)

    然后帐户类型应该从帐户对象中完全消失(如果没有,请取消映射)。要仅获取 UserAccount 记录,请使用

     .Accounts.OfType<UserAccount>()...
    

    Account 类在这个模型中应该是抽象的。接口的东西可以通过部分类添加 - 即在一个单独的文件中,定义:

    partial class Account : IAccount {
       // extra code here
    }
    

    一个合理的演练是here

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2016-03-11
      • 1970-01-01
      • 2023-03-24
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-04-16
      相关资源
      最近更新 更多