Entity Framework中的类和接口层次结构?

11

我有两个相关的类,它们共享一个公共接口,并且都存储在同一个底层数据库表中。然而,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; }
}
1个回答

14
这些数据是否被歧视了?即AccountType是否定义了它所属的类型?如果是这样的话:
  • EF应该从存储中创建Account实体
  • 然后你可以创建2个子类(UserAccount和GroupAccount)
  • 在Account的映射中,指定一个谓词“添加一个条件”
    • 让它将AccountType(存储)字段为1(或其他值)的记录映射到UserAccount
    • 让它将AccountType(存储)字段为2(或其他值)的记录映射到GroupAccount

然后,Account对象中的账户类型应该完全消失(如果没有对其进行映射)。要获取仅UserAccount记录,请使用:

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

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

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

这里有一个不错的指南,介绍了在Entity Framework中使用单表继承的方法here


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接