【发布时间】:2021-01-06 05:24:18
【问题描述】:
我有以下实体:
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属性而不是它们。
【问题讨论】:
-
这不是一个好的设计,我很确定你无法让它与 EF 一起使用。您应该有一个单独的实体(
Notification指向的实体),其中包含指向相关表格的链接。 -
只有
Poll和Test具有共同的基本类型并通过数据库继承(例如TPH 或TPT)映射到数据库时才有效,此外,您的NotifTypes枚举有问题 -
@AluanHaddad 你可以解释一下你在评论中写的答案的实现吗?
-
我的意思是
class Notification { public string Title { get; set; } public int Id { get; set; } }然后是class PollNotification: Notification { public Poll Poll { get; set;} }和class TestNotification: Notification { public Test Test { get; set; } }和class Poll { public ICollection<PollNotification> Notifications { get; set; } = new (); }等等。然后删除NotifTypes -
如果是直接查询通知,可以写
from pn db.Notifications.OfType<PollNotification>() where pn.Poll.Answer1 == "Biden or Trump" select pn;
标签: c# entity-framework code-first