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

asp.net-core-mvc asp.net-core-webapi entity-framework-core

Question

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

1
4
10/13/2017 1:16:06 PM

Popular Answer

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
3
12/14/2019 11:18:11 PM


Related Questions





Related

Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow