Error saving list of related objects

2

I'm using BeginCollectionItem to insert objects related to a Cliente that I call Dependentes .

When saving, I get the error:

  

Violation of the PRIMARY KEY constraint 'PK_dbo.Dependents'. It's not possible   insert the duplicate key into the object 'dbo.Dependents'. The value of   duplicate key is (00000000-0000-0000-0000-000000000000). The instruction   was completed.

Because in my list of objects, you are not generating a primary key. The object is arriving in the filled controller , only this detail is missing from generating a new primary key for every Dependente that is related to Cliente .

How can I do this? Here is the controller code:

[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);
}

    
asked by anonymous 05.05.2017 / 14:03

1 answer

4

You already know the cause of the error

  

Because in my list of objects, you are not generating a primary key

The solution is to create a new Guid for each Dependente , just as it is 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);
}
    
05.05.2017 / 14:06