2014-01-23 31 views
0

我有以下表,如何在应该有多个表的表中映射外键?

标识 的EntityType ENTITYID 消息

根据的EntityType是什么,它将被映射到不同的表

如果的EntityType为1,则映射表是Table1 如果EntityType是2,那么映射表是表2

如何在实体框架工作中创建映射配置?

我使用MVC4和EF5

回答

0

我也有类似的设计问题,我无法找到一个EF(干净)的方式来做到这一点。如果您考虑底层数据库,那么它将是单个字段,它是引用不同表的外键 - 甚至可能吗?

我可以提出两种替代方法。首先,你可以定义可选的关系:

public class EntityTypeMap 
{ 
    public int Id { get; set; } 

    public virtual EntityType1 EntityType1 { get; set; } 
    public int? EntityType1Id { get; set; } 

    public virtual EntityType2 EntityType2 { get; set; } 
    public int? EntityType2Id { get; set; } 

    public string Message { get; set; } 
} 

第二(更好)选择是创建单独的模型,但是从同一个基类派生:

public class BaseMap 
{ 
    public int Id { get; set; } 
    public string Message { get; set; } 
} 

public class EntityType1Map : BaseMap 
{ 
    public virtual EntityType1 EntityType1 { get; set; } 
    public int? EntityType1Id { get; set; } 
} 

public class EntityType2Map : BaseMap 
{ 
    public virtual EntityType2 EntityType2 { get; set; } 
    public int? EntityType1Id { get; set; } 
}