6
I have the following situation: The user has defined an establishment, where he has filled in data in two tables, and intends to replicate/copy all the same data, changing only the id of the establishment. I have the tables:
The table Acidezimpurezahumidade_tbl or AIH as I have in the project, receives as a foreign key the Servicosid table.
In my function to replicate/copy the data, I receive an integer that contains the id of the establishment (idServicoIDSelected) that I will copy and a list with the id of the establishments (listEstab) to copy to:
[AcceptVerbs(HttpVerbs.Get)]
public JsonResult CriarCopiarEstab(List<int> listaEstab, int idServicoIDSelected, string serie, int numDoc)
{
try
{
var dados = db.DadosComerciais.Where(d => d.Serie == serie && d.NumDoc == numDoc).FirstOrDefault();
var servico = db.Servicos.Find(idServicoIDSelected);
var aih = db.AIH.Where(a => a.ServicosID == servico.ServicosID).ToList();
foreach (var item in listaEstab)
{
var newServico = new Servicos();
newServico = servico;
newServico.DadosComerciais = db.DadosComerciais.Find(serie, numDoc);
db.Servicos.Add(newServico);
db.SaveChanges();
var newAih = new List<AIH>();
foreach (var item2 in aih)
{
var newElementoAih = new AIH();
newElementoAih.AcidezDesconto = item2.AcidezDesconto;
newElementoAih.AcidezMax = item2.AcidezMax;
newElementoAih.AcidezTaxaExtraEur = item2.AcidezTaxaExtraEur;
//newElementoAih = item2; //TAMBEM JÁ EXPERIMENTEI ASSIM
db.AIH.Add(newElementoAih);
db.SaveChanges();
}
}
return Json(JsonRequestBehavior.AllowGet);
}
catch (Exception ex)
{
return Json(new { Result = "ERROR", Message = ex.Message }, JsonRequestBehavior.AllowGet);
}
}
Where I got the problem?
I can’t replicate the data, get the servicosID
corresponding to be inserted in the AIH table. If replicating only the Services table works well, 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 Object context. 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.
On which line exactly the error occurs?
– Leonel Sanches da Silva
Just when I do
saveChanges()
table of services– CesarMiguel
@Cesarmiguel Have you found a solution to the problem? You can post an answer with him for the staff to vote (you can even accept it as correct.
– Maniero