EF,如何有条件地包含一个导航属性,该属性的类型与另一个属性的值相关



我有以下实体:

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

现在我希望有条件地将相关的PollTest包含在Ref属性中。我应该如何实施它?

我想防止添加单独的ID,如PollIdTestId和。。。。到Notification,因为我确信每次只有其中一个有值,所以我希望有一个RefId和一个Ref属性,而不是它们。

我不知道EntityFramework,但你让我回答这个问题。

你基本上是在重新发明多态关联,这不是一个好的关系设计。你可以阅读我过去关于这个概念的一些答案:

  • 是否可以对两个可能的表之一执行MySQL外键
  • 为什么在多态关联中不能有外键
  • MySQL-有条件的外键约束

我倾向于回答MySQL的问题,但对于任何其他品牌的RDBMS,答案都是一样的。不能声明引用多个表的实际外键约束这一事实应该表明这种设计是不对的。

从数据建模的角度来看,最简单的解决方案是为每个潜在的表引用创建一个独立的属性。在给定的行中,除一个外,所有这些都将为NULL。

我不知道EntityFramework如何支持这一点@AluanHaddad的建议听起来不错。

尽量不要破坏关系概念。沿着这条路径是内部平台效应反模式。

最新更新