TryUpdateModel for JSON when using web API
I assume: typed models and entity. I am fooling this myself, but as I understand it, if you use post values ββin your API then they will be initialized with default values ββ(e.g. null for a string) or if you have included validation attributes then the API may crash the model Validation Step ...
I am having an issue where the created and updated timestamp was overridden in new and updated commands.? operator helped to create but update is disabled, then I found the DatabaseGenerated attribute that I need.
[Column("db_created")]
[DatabaseGenerated(DatabaseGeneratedOption.Computed)]
public DateTime? Created { get; set; }
If you don't want to overwrite some of the fields with your defaults, you will need to make a manual map with the current instance. Get this and update the values ββyou changed. NOTE. You will need to update the new object checked out from the database as EF now keeps track of this instance when saving changes.
For example:
// PUT: api/Customer/5
[ResponseType(typeof(void))]
public async Task<IHttpActionResult> PutCustomer(int id, Customer updatedCustomer)
{
if (!ModelState.IsValid)
return BadRequest(ModelState);
if (id != updatedCustomer.ID)
return BadRequest();
var currentCustomer = await db.Customers.FindAsync(id);
updatedCustomer.Created = currentCustomer.Created;
currentCustomer.Name = updatedCustomer.Name;
currentCustomer.Description = updatedCustomer.Description;
//This is nullable in the model e.g. public DateTime? Updated;
currentCustomer.Updated = null;
db.Entry(currentCustomer).State = EntityState.Modified;
try
{
await db.SaveChangesAsync();
}
catch (DbUpdateConcurrencyException)
{
if (!CustomerExists(id))
return NotFound();
else
throw;
}
return StatusCode(HttpStatusCode.NoContent);
}
source to share