Optional Entity Framework include

Asked

Viewed 1,244 times

1

I have a great deal of doubt here about Include of the Entity Framework.

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

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

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

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

Follows 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; }
    }
  • 2

    Are you sure this isn’t about where?

  • Do you have how to post the models? At least the part that makes the occurrence link with person.

  • I’m sure it’s not because of the Where. Absolute. Model posted

  • You can post the other model too?

  • Added. I cut some variables to simplify the model.

  • Perfect. The idea is to make it as simple as possible, only you had to keep the model statement Ocorrencia :p

  • Or Ocorrencia has Pessoa but Pessoa has not Ocorrencia?

  • That’s right. Many to one relationship.

  • That’s weird because Include makes one Left Join, it would be nice for you to see the query that is executed and try to understand what the problem is.

  • You disabled Lazy Loading?

  • If it is SQL SERVER, see SQL Profiler to identify the query that is running. In Application Name will appear Entity Framework and you can see what it is actually doing. When you open Profiler, go to File -> New Trace -> Will open Trace Properties and click Run. Then just observe, after running your EF routine. https://i.stack.Imgur.com/cajMz.png

  • @jbueno by SQL Profiler is making a Join Inner. Not a Left Join.

Show 7 more comments

1 answer

4


Actually, it is not an optional Include. It is a null accepting property.

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

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

Follow the model with correction.

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

Browser other questions tagged

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