Include optional Entity Framework

1

I have a big question here with regards to Include of the Entity Framework.

var ocorrencias = db.Ocorrencia
       .Include("Pessoa")
       .Where(c => c.Id > 1000).ToList();

I used Include because I need the object Ocorrencias with the property Pessoa filled in. (If there is a person), if there is no person, the business rule will treat.

My query should return 12 records. However, when I use Include the query return are six records, (only the records containing the Pessoa property).

How do I Include do the job of filling the property only if it exists while keeping my return correct?

Follow the 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; }
        [Display(Name = "Nome"), Required(ErrorMessage = "Nome da Pessoa")]
        public string nome { get; set; }
        [Display(Name = "E-mail")]
        public string email { get; set; }
        [Display(Name = "CPF")]
        public string cpf { get; set; }
    }
    
asked by anonymous 22.03.2017 / 01:26

1 answer

4

In fact, this is not an optional Include. This is a property that accepts nil.

The error was in Model because it did not allow null, so the query was being created with InnerJoin and not LeftJoin .

In this way, Include handled correctly, and after changing the Model to allow null, the return was correct.

Follow the model with the fix.

public partial class Ocorrencia
{
    [Key]
    public int id { get; set; }
    public Pessoa Pessoa { get; set; }
    public int? PessoaId { get; set; }
}
    
22.03.2017 / 23:10