TryUpdateModel for JSON when using web API

We have a TryUpdateModel in System.Web.ModelBinding to update the model with partially available data in the source.

How do I use this pattern in Web API? Let's say my JSON result only contains 9 out of 10 fields, do I need to set the field value one by one?

+3


source to share


1 answer


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);
    }

      

+1


source







All Articles