简体   繁体   English

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

[英]EF, How to conditionally include a navigation property that type of it related to value of another property?

I have the bellow entities:我有以下实体:

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; }
}

OK,好的,

  • When the Type property of Notification object is equal Poll , the RefId will fill by a PollIdNotification对象的Type属性等于PollRefId将填充一个PollId
  • When type is equal Test , the refId will fill by a TestId .当类型等于Test ,该refId将由填写TestId

Now I want conditionally include the related Poll or Test in Ref property .现在我想有条件地在Ref属性中包含相关的PollTest How should I implement it?我应该如何实施它?

I want prevent to add separate Ids like PollId , TestId and.... to Notification because I'm sure that each time just one of them has value, so I want have one RefId and one Ref property instead of them.我想防止向Notification添加单独的 Id,如PollIdTestId和.... 因为我确定每次只有其中一个具有值,所以我想要一个RefId和一个Ref属性而不是它们。

I don't know EntityFramework, but you asked me to answer this.我不知道 EntityFramework,但你让我回答这个。

You're basically reinventing which is not a good relational design.您基本上是在重新发明,这不是一个好的关系设计。 You can read a few of my past answers about this concept:你可以阅读我过去关于这个概念的一些回答:

I tend to answer MySQL questions, but the answer is the same for any other brand of RDBMS.我倾向于回答 MySQL 问题,但对于任何其他品牌的 RDBMS,答案都是一样的。 The fact that you cannot declare an actual foreign key constraint that references multiple tables should be a clue that this design is not right.您不能声明引用多个表的实际外键约束的事实应该是这种设计不正确的线索。

The easiest solution from a data modeling perspective is to create an independent attribute for each of your potential table references.从数据建模的角度来看,最简单的解决方案是为每个潜在的表引用创建一个独立的属性。 All but one of these will be NULL on a given row.在给定的行上,除了其中之一之外的所有内容都将为 NULL。

I have no idea how EntityFramework might support this.我不知道 EntityFramework 如何支持这一点。 @AluanHaddad's advice sounds good. @AluanHaddad 的建议听起来不错。

Try not to break relational concepts.尽量不要打破关系概念。 Down that path is the Inner-Platform Effect antipattern .沿着这条路走的是内部平台效应反模式

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM