I have two entities:
public class ParentThing
{
[Key]
public int Id { get; set; }
[Required]
public ChildThing TheFirstThing { get; set; }
public ChildThing TheSecondThing { get; set; }
}
public class ChildThing
{
[Key]
public int Id { get; set; }
[Required]
public string Code { get; set; }
public string Name { get; set; }
}
and a view model:
public class ParentViewModel
{
public string Message { get; set; }
public ParentThing ParentThing { get; set; }
}
and a view:
@using (@Html.BeginForm())
{
<label>Code 1</label>
@Html.EditorFor(model => model.ParentThing.TheFirstThing.Code)
<label>Name 1</label>
@Html.EditorFor(model => model.ParentThing.TheFirstThing.Name)
<label>Code 2</label>
@Html.EditorFor(model => model.ParentThing.TheSecondThing.Code)
<label>Name 2</label>
@Html.EditorFor(model => model.ParentThing.TheSecondThing.Name)
<input type="submit" value="Save" />
}
In my post back I add the ParentThing to the context and attempt to save changes. I receive a validation error on the Code property of the TheSecondThing property of the ParentThing as it is required.
What are some alternatives for saving an optional property that contains required properties?