C#C
C#17mo ago
19 replies
Angius

EF Core 1-1 relationship with automatic discriminator

I have a CommentsThread entity and multiple ICommentable entities (Blogpost, Profile, Document, etc.) that all reference it:
public sealed class CommentsThread
{
    public long Id { get; init; }
    //...
}
public interface ICommentable
{
    long CommentsThreadId { get; set; }
    CommentsThread CommentsThread { get; set; }
}
public sealed Blogpost : ICommentable
{
    public long CommentsThreadId { get; set; }
    public CommentsThread CommentsThread { get; set; }
}

now, I would like a way to easily find what the comments thread belongs to. Does it contain comments of a blogpost? User profile? Document?

One way I figured was to reverse the relationship, and instead have a bunch of nullable FKs in the CommentsThread entity, pointing to all the ICommentables. That way, I could do some
string type;
if (thread.BlogpostId is not null) type = "blogpost";
else if (thread.ProfileId is not null) type = "profile";
else if (thread.DocumentId is not null) type = "document";
else type = "unknown";

but it all seems iffy at best.

Ideally, what I would like instead, was some
public CommentsSource Source { get; private set; }
public long SourceId { get; private set; }

properties on the CommentsThread, with CommentsSource being an enum.

Problem is, I have nary a clue how to do that. I considered maybe computed columns, but they seemingly can only reference the current entity.
Was this page helpful?