コード例 #1
0
    public async Task<VehicleResponseViewModel> SaveVehicle(VehicleViewModel vm, string userName)
    {
      var response = new VehicleResponseViewModel();
      try
      {
        var user = _userService.GetUserByUsername(userName);
        var vehicle = _db.Vehicles.FirstOrDefault(t => t.Id == vm.Id);
        if(vehicle==null)
        {
          if (IsVehicleAlreadyExists(vm.RegistrationNo).IsSuccess)
          {
            response.IsSuccess = false;
            response.Message = "Vehcile already registered with system.";

            return response;
          }


          var vt = vm.ToModel();
          vt.UpdatedBy = user.Id;
          vt.CreatedBy = user.Id;
          vt.CreatedOn = DateTime.UtcNow;
          vt.UpdatedOn = DateTime.UtcNow;

          _db.Vehicles.Add(vt);
          await _db.SaveChangesAsync();
          response.Id = vt.Id;

          response.IsSuccess = true;
          response.Message = "New Vehicle has been added.";
        }
        else
        {
          vehicle.UpdatedOn = DateTime.UtcNow;
          vehicle.UpdatedBy = user.Id;
          vehicle.ProductionYear = vm.ProductionYear;
          vehicle.InitialOdometerReading = vm.InitialOdometerReading;
          vehicle.IsActive = vm.IsActive;


          _db.Vehicles.Update(vehicle);
          await _db.SaveChangesAsync();

          response.IsSuccess = true;
          response.Message = "Vehicle detail has been updated.";
        }
      }
      catch (Exception ex)
      {
        logger.LogError(ex.ToString());
        response.IsSuccess = false;
        response.Message = "Operation failed.Please try again.";
      }


      return response;
    }