实体框架中的类和接口层次结构? [英] Class and Interface hierarchies in Entity Framework?
问题描述
我有两个相关的类,它们共享一个公共接口,并且都存储在同一基础数据库表中。但是,实体框架会生成一个公共类,而我确实需要两个不同的类。我该如何解决?最好使用基类而不是接口吗?如何更改EF模型以提供映射到一个表的两个类?
I have two related classes which share a common interface and are both stored in the same underlying database table. However, the Entity Framework generates one common class, where I really need the two distinct classes. How do I resolve this? Is it best to use a base class rather than an interface? How do I change the EF model to provide two classes mapped over one table?
编辑:AccountType属性确定类的类型;用户或组。
the AccountType property determines the type of class; user or group.
一些简单的代码:
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; }
}
推荐答案
是否已区分此数据?即AccountType是否定义它是哪种类型?如果是这样的话:
Is this data discriminated? i.e. does AccountType define which type it is? If so:
- EF应该从存储中创建帐户实体
- 然后创建2个子类(UserAccount和GroupAccount)
- 在帐户映射中,指定谓词添加条件
- 拥有它映射到AccountType(存储)字段为1(或其他任何值)的UserAccount
- 将其映射到AccountType(存储)字段为2(或其他任何内容)的GroupAccount
- EF should create the Account entity from the storage
- you then create 2 subclasses (UserAccount and GroupAccount)
- in the mapping for Account, specify a predicate "add a condition"
- have it map to UserAccount where the AccountType (storage) field is 1 (or whatever)
- have it map to GroupAccount where the AccountType (storage) field is 2 (or whatever)
然后,帐户类型应从Account对象中完全消失(如果没有,则取消映射)。要仅获取UserAccount记录,请使用
The account type then should completely disappear from the Account object (unmap it if not). To get just the UserAccount records, you use
.Accounts.OfType<UserAccount>()...
在此模型中,Account类应该是抽象的。可以通过部分类添加接口材料-即在单独的文件中,定义:
The Account class should probably be abstract in this model. The interface stuff can be added via a partial class - i.e. in a separate file, define:
partial class Account : IAccount { // extra code here }
etc
一个合理的演练是此处。
这篇关于实体框架中的类和接口层次结构?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!