Error saving list of related objects

Asked

Viewed 463 times

2

I’m using the BeginCollectionItem to insert objects related to a Cliente which I call Dependentes.

When saving, I have the mistake:

Violation of PRIMARY KEY constraint 'Pk_dbo.Dependents'. Not possible insert duplicate key into dbo. Dependent object. The value of duplicate key is (00000000-0000-0000-0000-000000000000). The instruction was finalized.

Because, in my object list, it is not generating a primary key. The Object is coming to controller filled, just missing this detail of generating a new primary key for each Dependente that is related to the Cliente.

How can I do that? Here is the code of controller:

[HttpPost]
public ActionResult Criar(Cliente cliente)
{
    if (ModelState.IsValid)
    {
        cliente.ClienteId = Guid.NewGuid();
        db.Clientes.Add(cliente);
        db.SaveChanges();
        return RedirectToAction("Indice");  
    }

    ViewBag.PossibleUsuarios = db.Users;
    return View(cliente);
}

inserir a descrição da imagem aqui

1 answer

4


You already know the cause of the mistake

Because in my object list, you’re not generating a primary key

The solution is to create a new Guid for each Dependente, as it is done for Cliente.

[HttpPost]
public ActionResult Criar(Cliente cliente)
{
    if (ModelState.IsValid)
    {
        cliente.ClienteId = Guid.NewGuid();

        foreach(var dependente in cliente.Dependentes)
        {
            dependente.DependentesId = Guid.NewGuid();
        }

        db.Clientes.Add(cliente);
        db.SaveChanges();
        return RedirectToAction("Indice");  
    }

    ViewBag.PossibleUsuarios = db.Users;
    return View(cliente);
}

Browser other questions tagged

You are not signed in. Login or sign up in order to post.