Dissociating a record from a table that keeps me many to many relationships

0

I am working with C # Entity Framwork approach Code First, I am working with a many-to-many relationship, in which I have an intermediate table where I keep relationships. My problem is when I want to delete one, I show the code

public void RemoveModelos(Proveedor proveedor, List<EntidadesDominio.Modelo> modelos)
    {
        //validamos que haya algo que remover
        if (modelos == null || modelos.Count == 0)
            return;

        using (PosContext Context = new PosContext())
        {
            //recuperamos el terrotorio y sus empleados
            //esto es necesario porque el objeto donde se debe remover tiene que estar dentro del contexto de EF
            Proveedor proveedorSel = Context.Set<Proveedor>().Include("Modelos")
                .FirstOrDefault(x => x.ProveedorId == proveedor.ProveedorId);

            if (proveedor.Modelos == null || proveedor.Modelos.Count == 0)
                return;

            modelos.ForEach(x =>
            {
                //localizamos al modelo dentro de la coleccion que se recupero anteriormente
                EntidadesDominio.Modelo modeloRemove = proveedorSel.Modelos.First(e => e.ModeloId == x.ModeloId);
                //se remueve de la coleccion haciendo uso de la instancia
                proveedorSel.Modelos.Remove(modeloRemove);
            });

            Context.SaveChanges();
        }
    }

Do not enter modelos.ForEach(x=> The method I apply when I remove the check from a DataGridView.

private void dgvModelo_CellContentClick(object sender, DataGridViewCellEventArgs e)
    {
        //Detecta si se ha seleccionado el header de la grilla
        if (e.RowIndex == -1)
            return;
        if(dgvModelo.Columns[e.ColumnIndex].Name == "colSN")
        {
            //Se toma la fila seleccionada
            DataGridViewRow row = dgvModelo.Rows[e.RowIndex];
            //Se selecciona la celda del checkbox
            DataGridViewCheckBoxCell cellSeleccion = row.Cells["colSN"] as DataGridViewCheckBoxCell;

            if(Convert.ToBoolean(cellSeleccion.Value))
            {
                string mensaje = string.Format("Mensaje. \n\nSe ha seleccionado," +
                    " \nDescripcion: '{0}'", row.Cells["colDescripcion"].Value);
                MetroMessageBox.Show(this, mensaje, strModelo.nameEntity, MessageBoxButtons.OK,
                    MessageBoxIcon.Information);
            }
            else
            {
                Proveedor _proveedor = new Proveedor();
                _proveedor.ProveedorId = string.IsNullOrEmpty(txtProveedorId.Text)
                    ? 0
                    : Convert.ToInt32(txtProveedorId.Text);
                _proveedor.RazonSocial = txtRazonSocial.Text.Trim();
                _proveedor.NroDocumento = txtNroDocumento.Text;
                _proveedor.DocumentoIdentidad = ((EnumDocumentoEdentidad)(cboTipoDocumento.SelectedValue));
                _proveedor.CategoriaId = Convert.ToInt32(cboCategoria.SelectedValue);
                _proveedor.Direccion = txtDireccion.Text;
                _proveedor.Fijo = txtFijo.Text;
                _proveedor.Celular = txtCelular.Text;
                _proveedor.Representante = txtRepresentante.Text;
                _proveedor.Email = txtEmail.Text;
                List<Modelo> listRowCheck = GetChecked(dgvModelo, "colSN");
                _repositoryProveedor.RemoveModelos(_proveedor, listRowCheck);
                txtProveedorId.Text = Convert.ToString(_proveedor.ProveedorId);

                string mensaje = string.Format("Mensaje. \n\nSe ha quitado la seleccion," +
                    " \nDescripcion: '{0}'", row.Cells["colDescripcion"].Value);
                MetroMessageBox.Show(this, mensaje, strModelo.nameEntity, MessageBoxButtons.OK,
                    MessageBoxIcon.Information);
            }
        }
    }

The problem is that I can not disassociate what I indicated, it never enters the part where the ForEach is made.

Because there are no models in supplier.

    
asked by Pedro Ávila 28.06.2016 в 17:57
source

1 answer

0

The whole problem was fixed in the CellContentClick

event
    if (Convert.ToBoolean(cellSeleccion.Value))
            {
                var elementos = new List<Modelo>();
                //Aquí la respuesta en este IF:
                if (Convert.ToBoolean(row.Cells["colSN"].Value) == true)
                {
                    var model = new Modelo()
                    {
                        ModeloId = Convert.ToInt32(row.Cells["colCodigo"].Value),
                        Descripcion = Convert.ToString(row.Cells["colDescripcion"].Value)
                    };
                    elementos.Add(model);
                }

                Proveedor _proveedor = _repositoryProveedor.Single(x => x.ProveedorId == Helper.IdRow);

                if (_proveedor != null)
                    _repositoryProveedor.AsignarModelos(_proveedor, elementos);
            }

            else
            {
                var elementos = new List<Modelo>();
                //Aquí la respuesta en este IF:
                if (Convert.ToBoolean(row.Cells["colSN"].Value) == false)
                {
                    var model = new Modelo()
                    {
                        ModeloId = Convert.ToInt32(row.Cells["colCodigo"].Value),
                        Descripcion = Convert.ToString(row.Cells["colDescripcion"].Value)
                    };
                    elementos.Add(model);
                }

                Proveedor _proveedor = _repositoryProveedor.Single(x => x.ProveedorId == Helper.IdRow, 
                new List<Expression<Func<Proveedor, object>>>() { x => x.Modelos });

                if (_proveedor != null)
                    _repositoryProveedor.RemoveModelos(_proveedor, elementos);
            }
    
answered by 28.06.2016 / 23:52
source