Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p>In response to the current suggestions this is what I now have. </p> <p>Entities remain the same.</p> <p>The modified view model:</p> <pre><code>public class ParentViewModel { public string Message { get; set; } public string FirstThingCode { get; set; } public string FirstThingName { get; set; } public string SecondThingCode { get; set; } public string SecondThingName { get; set; } } </code></pre> <p>The modified view:</p> <pre><code>@using (@Html.BeginForm()) { &lt;label&gt;Code 1&lt;/label&gt; @Html.EditorFor(model =&gt; model.FirstThingCode) &lt;label&gt;Name 1&lt;/label&gt; @Html.EditorFor(model =&gt; model.FirstThingName) &lt;label&gt;Code 2&lt;/label&gt; @Html.EditorFor(model =&gt; model.SecondThingCode) &lt;label&gt;Name 2&lt;/label&gt; @Html.EditorFor(model =&gt; model.SecondThingName) &lt;input type="submit" value="Save" /&gt; } </code></pre> <p>The DTO:</p> <pre><code>public class ParentThingDTO { public ParentThingDTO(ParentViewModel model) { FirstThingCode = model.FirstThingCode; FirstThingName = model.FirstThingName; SecondThingCode = model.SecondThingCode; SecondThingName = model.SecondThingName; } public int Id { get; set; } public string FirstThingCode { get; set; } public string FirstThingName { get; set; } public string SecondThingCode { get; set; } public string SecondThingName { get; set; } public ParentThing GenerateEntity() { var thing = new ParentThing(); thing.TheFirstThing = new ChildThing { Code = FirstThingCode, Name = FirstThingName }; if (!string.IsNullOrWhiteSpace(SecondThingCode)) { thing.TheSecondThing = new ChildThing { Code = SecondThingCode, Name = SecondThingName }; } return thing; } } </code></pre> <p>The postback action in the controller:</p> <pre><code> [HttpPost] public ActionResult Create(ParentViewModel model) { try { var dto = new ParentThingDTO(model); var parentThing = dto.GenerateEntity(); using (var context = new QuantumContext()) { context.ParentThings.Add(parentThing); context.SaveChanges(); model.Message = "Saved"; } } catch (Exception ex) { model.Message = ex.Message; } return View(model); } </code></pre> <p>The null or whitespace test in the dto GenerateEntity method solves my initial problem of the MVC required property within the optional property. How does it look?</p>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload