I have an entity, Post:
public class Post
{
[Key]
[Required]
public int PostId { get; set; }
}
I have another entity, Response
:
public class Response
{
[Key]
[Required]
public int ResponseId{ get; set; }
public int PostId {get; set;}
public int ParentResponseId {get; set;}
}
The idea is, a Response
either has a ParentResponseId
defined, OR a PostId
- but never both. A Post
can have many Responses, and a Response
can have many Responses.
I never need to navigate from one to the other via virtual
properties, nor do I need lazy loading - I just need the constraints set up in the db.
I'm new to modelBuilder but this seems like a case where it would have to be used. I have a starting point:
modelBuilder.Entity<Response>()
.HasOptional(c => c.Post)
.HasForeignKey(u => u.PostId);
modelBuilder.Entity<Response>()
.HasOptional(c => c.Response)
.HasForeignKey(u => u.ParentResponseId);
Is this the correct way to handle an optional one-to-many? Is there any way to add a constraint that says "one or the other FK needs to be defined"? Any guidance here would be much appreciated.