title: How to keep original values of an entity while reloading related entities using Entity Framework Core when ModelState is not valid?
body: <p>Using ASP.NET Core and Entity Framework Core.</p>
  
  <p>When editing a record, I also load related "child" entities used for display purposes in the edit form.</p>
  
  <p>If the user submits a form with missing required fields, then <code>ModelState.IsValid</code> is false. <em>So far so good.</em></p>
  
  <p>When returning the non-updated values to the user (with an error message), how can I keep the original values posted by the user and also reload related entities? </p>
  
  <p>In the following simplified example the <code>dbcontext</code> queries the client record and includes the associated state table to display the state name.</p>
  
  <p>If the <code>ModelState</code> is not valid, the client record is returned to the user with the values the user submitted - but all the related <code>.Include</code> entities are null at this point. How can I repopulate the <code>.Include</code> entities without overwriting the view model submitted?</p>
  
  <pre><code>// GET
  public async Task&lt;IActionResult&gt; Edit(int clientId)
  {
      var client = _context.Client
                           .Include(x =&gt; x.State)
                           .Where(w =&gt; w.client_id == clientId
                           .FirstOrDefault();
      return View(client);
  }
  
  // POST
  [HttpPost]
  [ValidateAntiForgeryToken]
  public async Task&lt;IActionResult&gt; Edit(clientModel)
  {
     //verify: last_name
     if (clientModel.last_name == null)
     {
         ModelState.AddModelError(string.Empty, "Last name is required");
     }
  
     if (ModelState.IsValid)
     {
        // Update the record and redirect
        await _context.SaveChangesAsync();
        return RedirectToAction(nameof(Index), new { client_id = clientModel.client_id });
     }
  
     // model state is not valid! Return record submitted to the edit view
     // *** MISSING THE VALUES FROM THE RELATED ENTITY clientModel.State at this point
     return View(clientModel);
  }
  </code></pre>