[英]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,好的,
Type
property of Notification
object is equal Poll
, the RefId
will fill by a PollId
Notification
对象的Type
属性等于Poll
, RefId
将填充一个PollId
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
属性中包含相关的Poll
或Test
。 How should I implement it?我应该如何实施它?
I want prevent to add separate Ids like
PollId
,TestId
and.... toNotification
because I'm sure that each time just one of them has value, so I want have oneRefId
and oneRef
property instead of them.我想防止向
Notification
添加单独的 Id,如PollId
、TestId
和.... 因为我确定每次只有其中一个具有值,所以我想要一个RefId
和一个Ref
属性而不是它们。
I don't know EntityFramework, but you asked me to answer this.我不知道 EntityFramework,但你让我回答这个。
You're basically reinventing polymorphic-associations 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.