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:
If TryUpdateModelAsync
can be used in MVC Web API?
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
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:
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With