简体   繁体   中英

Entity Framework “Violation of primary key” with composite primary key

I'm getting the exception:

Violation of PRIMARY KEY constraint 'PK_dbo.Parcelas'. Cannot insert duplicate key in object 'dbo.Parcelas'. The duplicate key value is (0, 15). The statement has been terminated.

And I get this error even if I don't add stuff to the table Parcelas . See code below:

using (var trans = _db.Database.BeginTransaction())
{
    try
    {
        var f = cbxFornecedor.SelectedItem as Fornecedor;
        var c = new Compra
        {
            //load properties
        };
        _db.Compras.Add(c);
        foreach (var cada in _itens)
        {
            c.ListaProdutos.Add(new ListaProdutos
            {
                //load properties
            });
            _db.Produtos.Find(cada.ProdutoClasse.ProdutoId).Estoque += cada.Quantidade;

        }
        var conta = new Conta
        {
            //load properties
            ListaParcelas = new List<Parcela>() 
           //this is the property the decides if the code is going to run or not.
           //With it, i get the error, without it, it runs fine
        };
        if(rbtPrazo.Checked)
            for (var i = 0; i < nudParcelas.Value; i++)
                conta.ListaParcelas.Add(new Parcela
                {
                    //load properties
                });
        c.Conta = conta;
        _db.SaveChanges();
        trans.Commit();
        Close();
    }
    catch (Exception ex)
    {
        trans.Rollback();
        MessageBox.Show(this, ex.Message, @"Erro", MessageBoxButtons.OK, MessageBoxIcon.Error);
    }
}

The deal breaker is if I instantiate the list ListaParcelas . The model Parcela has a composite primary key, and I think that's the source of my problem, although I'm only guessing this. Here's the model:

public sealed class Parcela
{
    [Key, Column(Order = 1)]
    public int ParcelaId { get; set; }

    [Key, Column(Order = 2)]
    public int ContaId { get; set; }

    [Required]
    public decimal Valor { get; set; }

    [ForeignKey("ContaId")]
    public Conta Conta { get; set; }

    [Required]
    public DateTime Vencimento { get; set; }
}

FYI, this class is marked sealed only because ReSharper was asking it and the error was already happening before I did it.

I just posted a comment that made me think about something and it fixed my problem. The issue for me was that when you have a composite key, auto-increment doesn't work anymore (it seems very obvious to me now), so all I did was set the ParcelaId with the value of i in the loop the populates ListaParcelas . Now, I'll mark this as the answer, but if anyone shows me how to do it WITH auto-increment, I'll mark them down as the answer.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM