views:

39

answers:

1

Hi everybody im trying to add new items to master detail records and i get the error:

The INSERT statement conflicted with the FOREIGN KEY constraint "invOrden_InvOrdenDet_FK1". The conflict occurred in database "InventarioSIAIplus", table "dbo.InvOrden", column 'IDorden'. The statement has been terminated.

This error Happens when i add a new item to the detail.

Thanks for any help. CODE I'M USING FOR ADDING AND UPDATING THE THE DATA: InventarioSIAIplusEntities SIAplusContext = (InventarioSIAIplusEntities)(Session["context"]); InvOrden orden;

        if (txtIDorden.Text.Trim() == "")
        {
             orden = new InvOrden();
             orden.IDcentro = Convert.ToInt32(ddlCentros.SelectedValue);
             orden.estado = ddlEstadoOrden.SelectedValue;
             orden.fecha = DateTime.Now;
             orden.comentario = txtComentarioOrden.Text;
             orden.usuarioCrea = "Jeanc";                
             SIAplusContext.AttachTo("InvOrden",orden);              
        }
        else
        {
             int idorden = Convert.ToInt32(txtIDorden.Text.Trim());
             orden = SIAplusContext.InvOrdenes.Where(c => c.IDorden == idorden).First();
                //orden.lo.getOrden());                
             orden.estado = ddlEstadoOrden.SelectedValue;
             orden.fecha = DateTime.Now;
             orden.comentario = txtComentarioOrden.Text;
             orden.usuarioCrea = "Jeanc";

        }

        foreach (var item in DetalleMedicamentosOrden)
        {
            if (item.InvOrdenReference.Value == null)
            {
                item.InvOrden = orden;

            }
        }

        SIAplusContext.SaveChanges();

CODE FOR ADDING ITEMS TEMPORARY TO THE DETAIL

InventarioSIAIplusEntities SIAplusContext = (InventarioSIAIplusEntities)(Session["context"]); List meds = DetalleMedicamentosOrden;

         //Datos Detalle
        InvOrdenDet ordenDetalle = new InvOrdenDet();            
        ordenDetalle.cantidadSol = uscAgregarMedicamentos1.Cantidad;
        ordenDetalle.cantidadApr = uscAgregarMedicamentos1.CantidadAprobada;

        ordenDetalle.comentario=uscAgregarMedicamentos1.Comentario;
        ordenDetalle.comentario = uscAgregarMedicamentos1.Comentario;
        ordenDetalle.IDmedicamento=uscAgregarMedicamentos1.IDmedicamento;

        //Agrego el detalle a la lista de detalles que se va guardando en la memoria.
        meds.Add(ordenDetalle);

        //Paso la lista con el nuevo objecto actualizada.
        DetalleMedicamentosOrden = meds;

        //Consulto la lista con para hacer una proyeccion del query y trae el nombre del medicamento
        var medInfo = from a in DetalleMedicamentosOrden                          
                     select new { a,  a.cantidadSol, a.cantidadApr };

        //Cargo la data en el gridview.
        gvMedicamentosOrden.DataSource = medInfo;
        gvMedicamentosOrden.DataBind();

        //Mando a mostrar 
        mpePnMedicamentos.Show();
A: 

The error basically means that you are trying to add a row to the detail table without providing a legit FK from the master table.
I am guessing this happens when your if code block (txtIDorden.Text.Trim() == "") is executing which means you are dealing with a brand new orden object that does not have any EntityKey before saving. I can see that you are trying to explicitly set the detail object to the master through InvOrdenReference which does not make sense in your scenario. What I suggest is that set it through navigation property and let EF fix it up for you at runtime. So your foreach should be something like this:

foreach (var item in DetalleMedicamentosOrden) {
    if (item.InvOrdenReference.Value == null) {
        item.InvOrden = orden;                  
     }
}
Morteza Manavi
Hey Thanks for you answer and it makes sense but when i put the code the way you said i'm still having an error when i try to add and item to the details. The error "An object with the same key already exists in the ObjectStateManager." but the object is a new one. Thanks for your help.
Jean
No problem. Which EF version are you using? Also can you please post the code inside ordenRepository.Add() and efUnitOfWork.Save() methods?
Morteza Manavi
Hi, i'm using entity framework 4 with a template that i download from codeplex that implements the repository pattern.
Jean
public void Add(InvOrden entity) { Repository.Add(entity); }
Jean
public EFUnitOfWork() { Context = new InventarioSIAIplusEntities(); } public void Save() { Context.SaveChanges(); }
Jean
I make some changes to the code and remove the repository template and im having this error :"Violation of PRIMARY KEY constraint 'InvOrdenDet_PK'. Cannot insert duplicate key in object 'dbo.InvOrdenDet'.The statement has been terminated. "
Jean