简体   繁体   中英

ASP.NET Core 5 MVC / C#: change model's value according to another model

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

You'd have to find the models and update them

 _context.Add(trip);
    var driver = _context.Driver.Where(a=> a.ID == trip.DriverId).FirstOrDefault();
    driver.whateveryouneedtoupdate = trip.whateverfiled;
    
    _context.Update(driver);
    
    var vehicle = _context.Vehicle.Where(a=> a.ID == trip.VehicleId).FirstOrDefault();
    vehicle.whateveryouneedtoupdate = trip.whateverfiled;

_context.Update(vehicle)

        await _context.SaveChangesAsync();
        return RedirectToAction(nameof(Index));

You should have probably two API end points, one for 1.Adding Trip 2.Updating Trip.

Based on the endpoint you code should do

1.Adding Trip

    context.Add(Trip);
    var existingDriver = context.Driver.Where(x => x.Id == Trip.driverId).FirstOrDefault();
    if (existingDriver != null)
    {

        existingDriver.FiedlYouwantToUpdate = existingDriver.FiedlYouwantToUpdate +  Trip.FieldYouWantToUpdate;
        context.Update(existingDriver);
    }
    else
    {
        context.Add(newDriver);
    }

2.Updating Trip

    context.Update(Trip);
    var existingDriver = context.Driver.Where(x => x.Id = Trip.driverId).FirstOrDefault();
    if (existingDriver != null)
    {

        existingDriver.FiedlYouwantToUpdate = existingDriver.FiedlYouwantToUpdate +
                                                    Trip.FieldYouWantToUpdate;
        context.Update(existingDriver);
    }
    else
    {
        context.Add(newDriver);
    }

note: You should do this for both Vechicle, Driver

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM