目前,我对从父ID中获取子数据并用硬编码文本更新子数据有一些了解。家长班: `
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; }
}
`
儿童班
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; }
}
情况是,当我需要将所有子状态列更新为“确认”时,我需要先通过搜索rideId来找到父类,如果找到了游乐设施,它将更新其子类属性。我正在使用EF核心保存数据。
// 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");
}
}
当前,这是我保存或更新数据的逻辑,你们可以帮助我如何基于父ID更新子类。
答案 0 :(得分:0)
How to add/update child entities when updating a parent entity in EF
我得到了这个解决方案,并用其他资源对其进行了修改。
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();
}