C # MVC EF5 delete relationships

0

Hello, I'm developing an application using C # MVC and EF5 and I have the following problem: I have a client group management screen, in this group I can insert and remove clients, I use a relationship table between clients and groups called client_group_client (obviously it has relation to the client_group table), when I add a client to this group , I enter your information in a table on the screen:

Thecodeforeachoftheselinesissomethinglikethis:

<buttonclass="btn_remove">Remover</button> <input name="client_group_client[0].id_client" type="hidden" value="3">

<input name="client_group_client[0].id" type="hidden" value="3">

<input name="client_group_client[0].status" type="hidden" value="1">

<input name="client_group_client[0].datetime_inclusion" type="hidden" value="15/07/2014 10:06:24">

Cliente 3

If I insert a new client and save it, it will insert a record in the database, until it is working, the problem is when I try to remove one of those records, the object passed to it only comes with the active relations on the screen, I I do not know which one was removed to remove from the bank. Anyone have any ideas how to do this?

ClientGroupController controller:

[HttpPost]
    [ValidateAntiForgeryToken]
    public ActionResult Edit(client_group client_group, string actionSubmit, string urlReferrer)
    {
        repository.BeforeUpdate(client_group);
        if (!repository.Save())
        {
            setFlash("danger", repository.GetHtmlErrors());
            return View("~/Views/Person/ClientGroup/Edit.cshtml", client_group);
        }

        setFlash("success", I18n.T("Alert","RegisterSaveSucess"));


        if (actionSubmit == "saveAndBack")
            return Redirect(urlReferrer);
        else
            return View("~/Views/Person/ClientGroup/Edit.cshtml", client_group);
    }

Repository class (created by me to process data before / after modifying):

public override bool BeforeUpdate(client_group obj)
    {
        foreach (client_group_client register in obj.client_group_client)
        {
            register.id_client_group = obj.id;

            if (register.datetime_inclusion == null)
            {
                register.datetime_inclusion = DateTime.Now;
                register.status = client_group_client.ACTIVE;
                dbContext.Entry(register).State = EntityState.Added;
            }
            else
            {
                dbContext.Entry(register).State = EntityState.Modified;
            }
        }

        return base.BeforeUpdate(obj);
    }
    
asked by anonymous 15.07.2014 / 20:46

2 answers

0

I believe that the fact that you are sending an instruction to the Controller to which the membership record belongs may be the complicator.

The solution I'm going to go through is possibly quite different from what you imagined, but it's the simplest one from the point of view of MVC architecture.

I would do the following:

1. Change the Remove button to a normal link

@Html.ActionLink("Remover", "Delete", "ClientGroupClient", new { id = client_group_client[0].id })

2. User a Delete Action on the Controller ClientGroupClient, instead of the Controller ClientGroup

// Esta Action pode abrir uma View de confirmação, mas é opcional.
// Você pode implementar apenas a Action mais abaixo.
public ActionResult Delete(int id)
{
    var clientGroupClient = dbContext.ClientGroupClients.Single(x => x.Id == id);
    return View(clientGroupClient);
}

Note that to call this Action , it must be a POST request. This is not required, but I usually use this to ensure there is a confirmation for deletion from the registry, just for security.

[HttpPost, ActionName("Delete")]
public ActionResult DeleteConfirmed(int id)
{
    var clientGroupClient = dbContext.ClientGroupClients.Single(x => x.Id == id);
    var clientGroupId = clientGroupClient.ClientGroupId;

    dbContext.ClientGroupClients.Remove(clientGroupClient);
    dbContext.SaveChanges();
    return RedirectToAction("Details", "ClientGroups", new { id = clientGroupId });
}
    
16.07.2014 / 19:10
0

One of the ways to solve is:

  • Get the list of clients of the group as it is in your database (just so you know what has been removed);

  • Change / Refresh the list of clients by deleting / editing group clients and saving

Example:

[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Edit(client_group client_group, string actionSubmit, string urlReferrer)
{        
    //Obter a lista de clientes do grupo como está na sua base de dados
    var grupo = repository.ObterGrupoPorId(client_group.IdGroup);
    //Diferença entre as listas para você alterar/atualizar a lista de clientes
    var clientesPosEdicao = ObterClientesInformadosUsuario(client_group).Except(grupo.Clientes).ToList();
    //Alterar/Atualizar a lista de clientes do grupo
    grupo.Clientes = clientesPosEdicao;
    //restante de código desejado para salvar, redirecionar, etc.
}

Note: Code not tested

    
15.07.2014 / 21:33