I have the following situation: The user has defined an establishment, where it has filled data in two tables, and wants to replicate / copy the data all the same, changing only the id of the establishment. I have the tables:
ThetableAcidImpureza_Tblidad_tblorAIHasIhaveintheproject,receivestheServicosIDfromtheServicostableasaforeignkey.
Inmyfunctiontoreplicate/copythedata,Igetanintegerthatcontainstheidoftheestablishment(idServicoIDSelected)thatIwillcopyandalistwiththeid'softheestablishments(listStab)tocopy:
[AcceptVerbs(HttpVerbs.Get)]publicJsonResultCriarCopiarEstab(List<int>listaEstab,intidServicoIDSelected,stringserie,intnumDoc){try{vardados=db.DadosComerciais.Where(d=>d.Serie==serie&&d.NumDoc==numDoc).FirstOrDefault();varservico=db.Servicos.Find(idServicoIDSelected);varaih=db.AIH.Where(a=>a.ServicosID==servico.ServicosID).ToList();foreach(variteminlistaEstab){varnewServico=newServicos();newServico=servico;newServico.DadosComerciais=db.DadosComerciais.Find(serie,numDoc);db.Servicos.Add(newServico);db.SaveChanges();varnewAih=newList<AIH>();foreach(varitem2inaih){varnewElementoAih=newAIH();newElementoAih.AcidezDesconto=item2.AcidezDesconto;newElementoAih.AcidezMax=item2.AcidezMax;newElementoAih.AcidezTaxaExtraEur=item2.AcidezTaxaExtraEur;//newElementoAih=item2;//TAMBEMJÁEXPERIMENTEIASSIMdb.AIH.Add(newElementoAih);db.SaveChanges();}}returnJson(JsonRequestBehavior.AllowGet);}catch(Exceptionex){returnJson(new{Result="ERROR", Message = ex.Message }, JsonRequestBehavior.AllowGet);
}
}
Where do I get the problem?
I am not able to replicate the data, go get the servicosID
corresponding to insert in the AIH table. If replicating only the Services table works fine, now if I start copying the lists I always get the error:
InvalidOperationException was caught The changes to the database were committed successfully, but an error occurred while updating the context object. The ObjectContext might be in an inconsistent state. Inner exception message: A referential integrity constraint violation occurred: The property values that define the referential constraints are not consistent between principal and dependent objects in the relationship.