我有以下实体:
public class Notification
{
public int Id { get; set; }
public string Title { get; set; }
public Guid RefId { get; set; }
public Object Ref { get; set; } // << The navigation property: Sometime its type is Poll and sometime is Test, maybe I add other types too
public NotifTypes Type { get; set; }
}
public enum NotifTypes
{
Poll=1,
Test=2,
// Other NotifTypes here
}
//-------------------------------------------------------------------
public class Test
{
public int Id { get; set; }
public string Title { get; set; }
public IEnumerable<Notification> { get; set; }
}
public class Poll
{
public int Id { get; set; }
public string Answer1 { get; set; }
public string Answer2 { get; set; }
public IEnumerable<Notification> { get; set; }
}
好的,
- 当
Notification
对象的Type
属性等于Poll
时,RefId
将填充PollId
- 当类型等于
Test
时,refId
将填充一个TestId
现在我希望有条件地将相关的Poll
或Test
包含在Ref
属性中。我应该如何实施它?
我想防止添加单独的ID,如
PollId
、TestId
和。。。。到Notification
,因为我确信每次只有其中一个有值,所以我希望有一个RefId
和一个Ref
属性,而不是它们。
我不知道EntityFramework,但你让我回答这个问题。
你基本上是在重新发明多态关联,这不是一个好的关系设计。你可以阅读我过去关于这个概念的一些答案:
- 是否可以对两个可能的表之一执行MySQL外键
- 为什么在多态关联中不能有外键
- MySQL-有条件的外键约束
我倾向于回答MySQL的问题,但对于任何其他品牌的RDBMS,答案都是一样的。不能声明引用多个表的实际外键约束这一事实应该表明这种设计是不对的。
从数据建模的角度来看,最简单的解决方案是为每个潜在的表引用创建一个独立的属性。在给定的行中,除一个外,所有这些都将为NULL。
我不知道EntityFramework如何支持这一点@AluanHaddad的建议听起来不错。
尽量不要破坏关系概念。沿着这条路径是内部平台效应反模式。