I have a foreign key relationship in my database between two tables, one-to-many, which I used scaffold to create the DBContext:
modelBuilder.Entity<ParentTable>(entity =>
{
entity.Property(e => e.Id).HasColumnName("ID");
entity.Property(e => e.Name)
.HasMaxLength(255)
.IsUnicode(false);
});
modelBuilder.Entity<ChildTable>(entity =>
{
entity.Property(e => e.Id).HasColumnName("ID");
entity.Property(e => e.Action)
.HasMaxLength(100)
.IsUnicode(false);
entity.Property(e => e.ExclSetId).HasColumnName("parentID");
entity.HasOne(d => d.ParentTable).WithMany(p => p.ChildTables)
.HasForeignKey(d => d.ParentId)
.OnDelete(DeleteBehavior.ClientSetNull)
.HasConstraintName("FK_Child_Parent");
});
I then used Scaffolding to create a controller on the child, and the POST it generated looks like this:
[HttpPost]
public async Task<ActionResult<ChildTable>> PostExclusionStep(ChildTable childRec)
{
_context.ExclusionSteps.Add(childRec);
await _context.SaveChangesAsync();
return CreatedAtAction("GetChildRecord", new { id = childRec.Id }, childRec);
}
The class for the Child record, came with a virtual member pointing to the Parent record in it:
public virtual ParentTable MyParent { get; set; } = null!;
So I’m not totally surprised when I tried to post to it, and it said “Bad Request” that “Validation Failed”, and that “MyParent” was required. My question is, what does it expect me to do, only post from the parent, or am I supposed to do a GET on the parent first in the front-end, and re-post as a full graph? I’m stuck on the concept of “Scaffolding must be useful somehow”, but if I have to build every graph separately I’m not sure what good the code was.
Can someone provide insight on how to best handle?