Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Update model with TryUpdateModel in ASP.NET MVC Core Web API and Entity Framework Core doesn't work

I'm new to ASP.NET MVC Core Web API and EF Core, and I'm creating a simple MVC web API demo as follows.

[HttpPut("{id}")]
public async void Put(int id, [FromBody]Student student)
    {
        if (ModelState.IsValid)
        {
            var stu = _context.Students
                .Where(s => s.StudentId == id)
                .SingleOrDefault();

            var updateResult = await TryUpdateModelAsync<Student>(stu, "", s => s.FirstName, s => s.LastName, s => s.EnrollmentDate);
            _context.SaveChanges();
        }

    }

The problem is that TryUpdateModelAsync doesn't work, the changes didn't get updated to the database.

I wonder:

  1. If TryUpdateModelAsync can be used in MVC Web API?

  2. I really don't want to write boring code like the following, how do I avoid doing the property value settings from one object to another of the same type? (that's the very first reason why I used TryUpdateModelAsync)

    stu.FirstName = student.FirstName;
    stu.LastName = student.LastName;
    stu.SomeOtherProperties = student.SomeOtherProperties;
    _context.SaveChanges();
    

.NET Core version: 1.1.0

ASP.Net Core version: 1.1.0

Entity Framework Core version: 1.1.0

like image 466
James L. Avatar asked Dec 31 '16 16:12

James L.


1 Answers

Web API generally use a DTO The official docs show the correct approach.

See GitHub issue TryUpdateModelAsync() doesn't work for ASP.NET Core MVC Web API for the definitive answer.

The [FromBody] attribute uses formatters to deserialize the request body into an object (e.g. using JSON or XML).

On the other hand, model binding, which includes the TryUpdateModel API, uses value providers to get data from the form body (if any), query string, route data, or some other places.

There are a few ways to go here:

  1. You could certainly write the "boring" code. Or you could look at using a library such as AutoMapper that does this "left-hand/right-hand" operation automatically.
  2. You could change the posted data to be a form post, in which case model binding will work just fine.
  3. You could change the posted data to use the JSON PATCH protocol, which was created for exactly this scenario. There's a great blog post about how to do that with ASP.NET Core: http://benfoster.io/blog/aspnet-core-json-patch-partial-api-updates
like image 132
RickAndMSFT Avatar answered Sep 19 '22 22:09

RickAndMSFT