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 ofNotification
object is equalPoll
, theRefId
will fill by aPollId
- When type is equal
Test
, therefId
will fill by aTestId
.
Now I want conditionally include the related Poll
or Test
in Ref
property. 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
points to) that has the links to the relevant tables. – QuadripartitePoll
andTest
have a common base type and are mapped to the database via DB inheritance, such as TPH or TPT, also, yourNotifTypes
enum is problematic – Decareclass Notification { public string Title { get; set; } public int Id { get; set; } }
thenclass PollNotification: Notification { public Poll Poll { get; set;} }
andclass TestNotification: Notification { public Test Test { get; set; } }
andclass Poll { public ICollection<PollNotification> Notifications { get; set; } = new (); }
etc. Then removeNotifTypes
– Decarefrom pn db.Notifications.OfType<PollNotification>() where pn.Poll.Answer1 == "Biden or Trump" select pn
; – DecareNotification
subclasses will introduce foreign key properties into theNotifications
table, one referencingPoll
and the otherTest
. Otherwise, you won't be able to have a navigation property as you describe. – Decare