Entity - Multiplicity Constraint violated

Asked

Viewed 297 times

2

I don’t understand the reason for this error in Entity. Could you give me a help?

Error: The role 'Occurrence_occurrence_target' of the Relationship 'Addresseb.Models.Occurrence_occurrence' has multiplicity 1 or 0.. 1.

Model:

public partial class Ocorrencia
{
    [Key]
    public int id { get; set; }
    public Pessoa Pessoa { get; set; }
    public int? PessoaId { get; set; }
    public virtual ICollection<OcorrenciaHistorico> Historico { get; set; }

    public Ocorrencia()
    {
        Historico = new HashSet<OcorrenciaHistorico>();
    }
}

public class Pessoa
{
    [Key]
    public int id { get; set; }
    public string nome { get; set; }
}

public class Historico
{
    [Key]
    public int id { get; set; }
    public DateTime DataCadastro { get; set; }

    public Pessoa pessoa { get; set; }
    public int pessoaId { get; set; }

    public int OcorrenciaId { get; set; }
    public virtual Ocorrencia Ocorrencia { get; set; }
}

The error happens when saving after adding an object to the history.

Ocorrencia.Historico.Add(new OcorrenciaHistorico() { Acao = "Criação", DataCadastro = DateTime.Now, Ocorrencia = Ocorrencia, pessoa = pessoa });
  • 1

    What’s the rest of the mistake?

  • @Ciganomorrisonmendez I edited the question adding this information.

1 answer

2


The context is understanding that pessoa is a new Person, not an existing person.

It’s better to do it like this:

var pessoa = db.Pessoas.Include(p => p.Ocorrencias).Where(...);
var ocorrencia = pessoa.Ocorrencias.Where(...);
ocorrencia.Historico.Add(new OcorrenciaHistorico() { Acao = "Criação", DataCadastro = DateTime.Now });
db.Entry(ocorrencia).State = EntityState.Modified;
db.SaveChanges();

Or selecting by Occurrence also.

var ocorrencia = db.Ocorrencias.Include(o => o.Pessoa).Where(...);
ocorrencia.Historico.Add(new OcorrenciaHistorico() { Acao = "Criação", DataCadastro = DateTime.Now });
db.Entry(ocorrencia).State = EntityState.Modified;
db.SaveChanges();

Browser other questions tagged

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