I need to insert parent record through for loop and based on newly generate ID need to create child records, but EF doesn't seem to be working well.
Based on answers suggested in different stackoverflow questions, I call db.savechanges()
after all foreach
loop but it's just creating two records whereas foreach
loop contains 6 items.
Exception:
System.InvalidOperationException: 'The changes to the database were committed successfully, but an error occurred while updating the object context. The ObjectContext might be in an inconsistent state. Inner exception message: A referential integrity constraint violation occurred: The property value(s) of 'new_job.job_id' on one end of a relationship do not match the property value(s) of 'job_address_point.job_id' on the other end.'
InvalidOperationException: A referential integrity constraint violation occurred: The property value(s) of 'new_job.job_id' on one end of a relationship do not match the property value(s) of 'job_address_point.job_id' on the other end.
Code:
foreach (var cartype in cartypes)
{
if (cartype.TotalCar != 0)
{
for (int i = 0; i < cartype.TotalCar; i++)
{
//new_job job = new new_job();
//new_job_db object same as new_job where I'm assigning all values to properties
//received in parameter
new_job job = new_job_db.CloneJson();
job.job_ref = str + createRandomNumber();
job.car_type_id = cartype.CarTypeId;
db.new_job.Add(job);
db.SaveChanges();
var jobId = job.job_id;
var jobDate = job.job_date;
//multi address
foreach (SelectedPoint p in _newjobdto.addresses)
{
job_address_point addr = new job_address_point();
addr.job_id = jobId;
addr.passenger_id = passengerId;
addr.job_date = jobDate;
addr.point_seq = Convert.ToInt32(p.PointSeq);
addr.place_id = p.PlaceId;
addr.formatted_address = p.FormattedAddress;
addr.lat = p.Lat;
addr.lng = p.Lng;
addr.post_code = p.PostCode;
addr.zone_name = p.ZoneName;
addr.mile = p.Miles;
addr.km = p.Kms;
addr.charges = p.Charges;
db.job_address_point.Add(addr);
}
db.SaveChanges();
}
}
}
Update:
Here are debug result: on 1st round it generate the Id and on 2nd round it throwing the exception:
Update:
As comment to Gabriel Luci answer, I implemented CloneJson() extension method from this question but its giving same error. I want to take the processing of 20 properties outside of foreach loop and copy it into newly create object inside the foreach loop where there only two properties need to set.