title: Web Api Updating only specific properties through a binding model
body: <p>We are currently building a web api and controllers for each of our data tables with basic CRUD functionality. The issue we are running into is with Updates. We've created custom binding models to bring in only the data we need, then convert that binding model to an object, and pass it to our update function.</p>
  
  <p>The problem we are running into is that when the client sends data through a POST, our binding model recieves it and populates the fields they set with the values, and everything else it populates as null. So when we convert it to the data object and send it to the Update function it overrides fields that weren't set from the client to null.</p>
  
  <p>This is obviously going to cause issues as we don't want users to be accidentally deleting information.</p>
  
  <p>Here is an example of how we are running things with the client, binding model, and updates,</p>
  
  <p><strong>The Team Binding Model</strong></p>
  
  <pre><code>/// &lt;summary&gt;A Binding Model representing the essential elements of the Team table&lt;/summary&gt;
  public class TeamBindingModel
  {
      /// &lt;summary&gt;The Id of the team&lt;/summary&gt;
      [Required(ErrorMessage = "An ID is required")]
      public int ID { get; set; }
  
      /// &lt;summary&gt;The name of the team&lt;/summary&gt;
      [Required(ErrorMessage = "A Team Name is required")]
      [Display(Name = "Team Name")]
      [StringLength(35)]
      public string Team1 { get; set; }
  
      /// &lt;summary&gt;The email associated with the team&lt;/summary&gt;
      [StringLength(120)]
      [DataType(DataType.EmailAddress)]
      public string Email { get; set; }
  
      public bool ShowDDL { get; set; }
  }
  </code></pre>
  
  <p><strong>The UpdateTeam CRUD Method</strong></p>
  
  <pre><code>// PUT: api/Team
  /// &lt;summary&gt;
  /// Attempt to update a team with a given existing ID
  /// &lt;/summary&gt;
  /// &lt;param name="team"&gt;TeamBindingModel - The binding model which needs an Id and a Team name&lt;/param&gt;
  /// &lt;returns&gt;IHttpActionResult that formats as an HttpResponseCode string&lt;/returns&gt;
  [HttpPut]
  [Authorize(Roles = "SystemAdmin.Teams.Update")]
  public async Task&lt;IHttpActionResult&gt; UpdateTeam(TeamBindingModel team)
  {
      if (!ModelState.IsValid)
      {
          return BadRequest(ModelState);
      }
  
      try
      {
          // Convert the binding model to the Data object
          Team teamObject = team.ToObject();
  
          unitOfWork.TeamRepository.Update(teamObject);
          await unitOfWork.Save();
      }
      catch (DbUpdateConcurrencyException)
      {
          return BadRequest();
      }
      catch (Exception ex)
      {
          return BadRequest(ex.Message);
      }
  
      return Ok();
  }
  </code></pre>
  
  <p><strong>The ToObject Function</strong></p>
  
  <pre><code>/// &lt;summary&gt;Takes the Team Binding model and converts it to a Team object&lt;/summary&gt;
  /// &lt;returns&gt;Team Object&lt;/returns&gt;
  public virtual Team ToObject()
  {
      // Setup the data object
      Team newObject = new Team();
  
      // Instantiate the basic property fields
      newObject.ID = this.ID;
      newObject.Team1 = this.Team1;
      newObject.Email = this.Email;
      newObject.ShowDDL = this.ShowDDL;
  
      return newObject;
  }
  </code></pre>
  
  <p><strong>The Update Function</strong></p>
  
  <pre><code>public virtual void Update(TEntity entityToUpdate)
  {
      try
      {
          dbSet.Attach(entityToUpdate);
          dbContext.Entry(entityToUpdate).State = EntityState.Modified;
      }
      catch (Exception ex)
      {
          throw ex;
      }
  }
  </code></pre>
  
  <p><strong>The Save Function</strong></p>
  
  <pre><code>public async Task Save()
  {
      await dbContext.SaveChangesAsync();
  }
  </code></pre>
  
  <p><strong>Client calls / Testing / Error</strong></p>
  
  <pre><code>// Add team to update and remove
  var db = new genericDatabase();
  var teamDB = new Team { Team1 = "testTeam", Email = "test@email.com", ShowDDL = true};
  
  db.Teams.Add(teamDB);
  db.SaveChanges();
  
  // Look for items in the database
  var originalTeamInQuestion = (from b in db.Teams
                                  where b.Team1 == "testTeam"
                                  select b).FirstOrDefault();
  
  // Create Team object with the some changes
  var team = new
  {
      ID = originalTeamInQuestion.ID,
      Team1 = "changedTestTeam",
      ShowDDL = false,
  };
  
  // This is the API call which sends a PUT with only the parameters from team
  var teamToUpdate = team.PutToJObject(baseUrl + apiCall, userAccount.token);
  
  // Look for items in the database
  var changedTeamInQuestion = (from b in db.Teams
                                  where b.Team1 == "changedTestTeam"
                                  select b).FirstOrDefault();
  
  // This Assert succeeds and shows that changes have taken place
  Assert.AreEqual(team.Team1, changedTeamInQuestion.Team1);
  
  // This Assert is failing since no Email information is being sent
  // and the binding model assigns it to Null since it didn't get that 
  // as part of the PUT and overrides the object on update.
  Assert.AreEqual(originalTeamInQuestion.Email, changedTeamInQuestion.Email);
  </code></pre>
  
  <p>Any ideas on some alternative approaches to this? We've thought of asking the client to first get the whole object by making a GET call to the API and then altering the object, but if a client doesn't follow that protocol they can very dangerously wipe out sensitive data.</p>