Romias
Romias

Reputation: 14133

Query using EF "Include" and including the related tables on Where

So far, I thought I could do:

 var num = db.MyTable.Include(x => x.RelatedTable)
           .Count( x.idTenant == CurrentTenantID && x.Active &&
              x.RelatedTable.SomeProperty.Value == true);

This always return zero records. Am I assuming wrongly that Including the RelatedTable I can use it in the where part?

By the way... the "SomeProperty" is Nullable, that is why the ".Value".

I'm using Entity Framework 4.1. (Database first)

Upvotes: 0

Views: 324

Answers (2)

AJ.
AJ.

Reputation: 16719

Are you trying to get the number of records? If so, why do you even need the Include? Entity Framework will lazy-load the RelatedTable entity set for you when it evaluates your Count condition. Also, if SomeProperty is a bool?, you should check if it has a value before you check the value itself.

var num = db.MyTable.Count(x => 
    x.idTenant == CurrentTenantID && 
    x.Active && 
    (x.RelatedTable.SomeProperty.HasValue && 
     x.RelatedTable.SomeProperty.Value));  

Upvotes: 1

Ladislav Mrnka
Ladislav Mrnka

Reputation: 364249

You don't need to use Include if you only want to access navigation property in Where part. Include is only used to fetch (eager load) related records together with the main record from database to your application but it doesn't make sense if you only want to count records.

Upvotes: 1

Related Questions