Entity Framework - Deleting object with relationship

4

I have a question for understanding the behavior of Entity. Because when I pass null to a property the Entity should not "clean" the relationship in the bank?

My Model:

public partial class Ocorrencia
{
    [Key]
    public int id { get; set; }
    public Pessoa Pessoa { get; set; }
    public int? PessoaId { get; set; }
}

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

My Context:

public System.Data.Entity.DbSet<MoradaWeb.Models.Ocorrencia> Ocorrencia { get; set; }

It turns out that when I call the command:

var Ocorrencia = db.Ocorrencia.FirstOrDefault(c => c.id == id);
Ocorrencia.Pessoa = null;

The PersonaId property is not being "zeroed".

  

Should not Entity zero the PersonaID property automatically?

NOTE: The object search is already being done correctly (with the Person object filled in according to the id in PersonId)

    
asked by anonymous 29.03.2017 / 19:29

1 answer

3

You did not load Pessoa . You need to load the object into the context to see it:

var Ocorrencia = db.Ocorrencia
                   .Include(o => o.Pessoa)
                   .FirstOrDefault(c => c.id == id);

Ocorrencia.Pessoa = null;
db.SaveChanges();
    
29.03.2017 / 19:36