Skip to content
Advertisement

How to update existing child class by using the parent id

Currently I have somes idea where we get the child data from its parent Id, and update the child data with hardcoded text. Parent Class: `

public class Ride
    {
        [DatabaseGenerated(DatabaseGeneratedOption.Identity)]
        public int Id { get; set; }
        public DateTime RideStartTime { get; set; }
        public string DestinationLongitude { get; set; }
        public string DestinationLatitude { get; set; }
        public int SeatAvailable { get; set; }
        public Double TotalCost { get; set; } = 0;
        public Double TotalDistance { get; set; } = 0;

        //Ride has Many Request
        public ICollection<Request> Requests { get; set; }


    }

`

Child Class

  public class Request : IEntity
{
    [Key]
    [DatabaseGenerated(DatabaseGeneratedOption.Identity)]
    public int Id { get; set; }

    [Required]
    public string PickupLongitude { get; set; }
    [Required]
    public string PickupLatitude { get; set; }

    public Double? EstimatedCost { get; set; } = 0;
    public Double? Rating { get; set; } = 0;
    public int RideId { get; set; }
    public Ride Ride { get; set; }


}

The situation is when the when i need to update all child status column to “Confirm”, i need to find it parent class first by search the rideId and if the ride found, it will update their child class attribute. Im using EF core to save the data.

  // PUT api/<controller>/5
    [HttpPut("{id}/confirm")]
    public IActionResult ConfirmRide(int id, [FromBody]Ride ride)
    {
        try
        {
            if (ride.IsObjectNull())
            {
                _logger.LogError("Ride object sent from client is null.");
                return BadRequest("Ride object is null");
            }

            if (!ModelState.IsValid)
            {
                _logger.LogError("Invalid ride object sent from client.");
                return BadRequest("Invalid model object");
            }

            var dbRide = _repository.Ride.GetRideById(id);
            if (dbRide == null)
            {
                _logger.LogError($"Ride with id: {id}, hasn't been found in db.");
                return NotFound();
            }

            _repository.Ride.ConfirmRide(dbRide, ride, id, "Confirmed");
            //_repository.Ride.
            _repository.Save();

            return NoContent();
        }
        catch (Exception ex)
        {
            _logger.LogError($"Something went wrong inside UpdateRide action: {ex.Message}");
            return StatusCode(500, "Internal server error");
        }
    }

Currently this is my logic to save or update the data, can you guys help me how to update the child class base on parent Id.

Advertisement

Answer

How to add/update child entities when updating a parent entity in EF

I got this solution and modify it with other resource.

 public void ConfirmRide(Ride dbRide, int id, string status)
    {
        dbRide.MapStatus(status);
        Update(dbRide);
        var existingParent = RepositoryContext.Rides
                             .Where(p => p.Id == id)
                             .Include(p => p.Requests).Where(r => r.Requests.Any( request => request.Status == "Approved"))
                             .SingleOrDefault();
        if (existingParent != null)
        {

            foreach (var existingChild in existingParent.Requests.ToList())
            {
                existingChild.Status = "Confirmed";
            }

        }
        RepositoryContext.SaveChanges();


    }
User contributions licensed under: CC BY-SA
6 People found this is helpful
Advertisement