According to the accepted answer here: The relationship could not be changed because one or more of the foreign-key properties is non-nullable
I've already deleted all child items before updating the entity using entity.Children.Clear()
:
public static JsonViewData AddOrUpdate(ModelDBContext context, GENCompanyViewModel companyModel, string userName, string userId)
{
try
{
var company = new GENCompany();
if (companyModel.Id > 0) //Update
{
company = context.Companies.Find(companyModel.Id);
context.Entry(company).State = EntityState.Modified;
company.Vehicles.Clear();
company.Phones.Clear();
company.Emails.Clear();
company.InjectFrom(companyModel);
company.DateUpdated = DateTime.Now;
}
else //Add
{
company.InjectFrom(companyModel);
company.CreatedById = new Guid(userId);
context.Companies.Add(company);
context.SaveChanges(userName);
}
if (companyModel.Vehicles.Any())
{
foreach (var vehicleModel in companyModel.Vehicles)
{
var vehicle = context.Vehicles.Find(vehicleModel.Id);
context.Entry(vehicle).State = EntityState.Unchanged;
company.Vehicles.Add(vehicle);
}
}
if (companyModel.Phones.Any())
{
foreach (var phoneModel in companyModel.Phones)
{
var phone = new GENCompanyPhone();
phone.InjectFrom(phoneModel);
company.Phones.Add(phone);
}
}
if (companyModel.Emails.Any())
{
foreach (var emailModel in companyModel.Emails)
{
var email = new GENCompanyEmail();
email.InjectFrom(emailModel);
company.Emails.Add(email);
}
}
context.SaveChanges(userName);
return new JsonViewData { IsSuccess = true, Message = "Added Successfully" };
}
catch (Exception ex)
{
return new JsonViewData { IsSuccess = false, Message = ex.InnerException?.InnerException?.Message ?? ex.InnerException?.Message ?? ex.Message };
}
}
and I get this error:
The operation failed: The relationship could not be changed because one or more of the foreign-key properties is non-nullable. When a change is made to a relationship, the related foreign-key property is set to a null value. If the foreign-key does not support null values, a new relationship must be defined, the foreign-key property must be assigned another non-null value, or the unrelated object must be deleted.