ASP.NET Core 5 MVC / C#:根据另一个模型更改模型的值



我是ASP新手。. NET Core 5 MVC应用。我添加了3个模型到我的应用程序。这些是Trip,VehicleDriver

VehicleLastTripDateTime,TotalTravelDistanceInKilometers,AverageFuelConsumptionInLitres

DriverUsedVehicleCount

当在Trip模型中添加新记录或更改任何记录时,我必须从VehicleDriver更改这些值。

我该怎么做呢?这些动作应该在哪里,我需要使用哪些方法?

我有控制器和视图。CRUD选项可用。我修改了Trip的基本脚手架创建操作,如下所示。这能起作用吗?

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

您应该有两个API端点,一个用于1.添加旅行2.更新旅行。

基于端点,代码应该执行

1。添加访问

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。更新访问

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

注意:您应该对vehicle, Driver都这样做

您必须找到模型并更新它们

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

相关内容

  • 没有找到相关文章

最新更新