Entity Framework - Object exclusion with relationship

Asked

Viewed 65 times

4

I have a question to understand the behavior of Entity. Because when I pass null Entity should not "clean up" 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; }

Turns out when I call command:

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

Personal property is not being "reset".

Entity should not reset the Personal property automatically?

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

1 answer

3


You did not charge Pessoa. You need to load the object for the context to observe it:

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

Ocorrencia.Pessoa = null;
db.SaveChanges();

Browser other questions tagged

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