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?
As jamie suggested, remove any dependencies between your entities and your models...they're 2 separate things Don't use data annotations on your entities, use data annotations on your models. Remove the ParentThing property of your model and add as primitive properties in your model as you need (i.e. Message, ParentThingId, TheFirstThingId, TheFirstThingCode, TheFirstThingName, etc) and add all your data annotation attributes to the model. If you need to validate your entities (you probably will) do that on your business logic.
I hope it makes sense
Leo.