I am new to ASP.NET Core 5 MVC apps. I added 3 models to my app. These are Trip, Vehicle and Driver.
Vehicle has LastTripDateTime, TotalTravelDistanceInKilometers, AverageFuelConsumptionInLitres.
The Driver has UsedVehicleCount.
When a new record added or any record changed in the Trip model, I have to change these values from Vehicle and Driver.
How can I do that? Where these actions should be in and which methods I need to use?
I have controllers and views. CRUD options are available. I modified basic scaffolded create action for Trip like below. Does this work?
// POST: Trips/Create
// To protect from overposting attacks, enable the specific properties you want to bind to.
// For more details, see http://go.microsoft.com/fwlink/?LinkId=317598.
[HttpPost]
[ValidateAntiForgeryToken]
public async Task<IActionResult> Create([Bind("TripId,VehicleId,DriverId,DistanceInKilometers,FuelConsumptionInLitres")] Trip trip)
{
if (ModelState.IsValid)
{
_context.Add(trip);
Driver driver = _context.Find<Driver>(trip.DriverId);
driver.UsedVehicleCount += 1;
await _context.SaveChangesAsync();
return RedirectToAction(nameof(Index));
}
return View(trip);
}