问题 实体框架中的类和接口层次结构?


我有两个相关的类,它们共享一个公共接口,并且都存储在同一个底层数据库表中。但是,实体框架生成一个公共类,我真的需要两个不同的类。我该如何解决这个问题?最好使用基类而不是接口吗?如何更改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; }
}

7971
2017-12-09 16:05


起源



答案:


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

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

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

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

在此模型中,Account类可能应该是抽象的。接口内容可以通过部分类添加 - 即在单独的文件中,定义:

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

等等

一个合理的演练是 这里


14
2017-12-09 16:09



..你尽快回答他们,谢谢;) - flesh


答案:


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

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

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

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

在此模型中,Account类可能应该是抽象的。接口内容可以通过部分类添加 - 即在单独的文件中,定义:

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

等等

一个合理的演练是 这里


14
2017-12-09 16:09



..你尽快回答他们,谢谢;) - flesh