Avoiding DbSet objects count using ToList() <p>Using C# Entity Framework v6.1.1, I was trying to make a Count operation on a <code>DbSet</code>:</p> <pre><code>//Items is a List&lt;Item&gt; int count = db.MyObjects.Count(o =&gt; o.Items.FirstOrDefault(i =&gt; i.ItemID == 1) != default(Item)); </code></pre> <p>I did not use Contains, as there is a known EF issue on its use with Where Count etc.</p> <p>Now, the above line throws an NullReferenceException, telling me that object reference is not set to an instance of object.</p> <p>Changing it to:</p> <pre><code>//Items is a List&lt;Item&gt; int count = db.MyObjects.ToList().Count(o =&gt; o.Items.FirstOrDefault(i =&gt; i.ItemID == 1) != default(Item)); </code></pre> <p>Works as expected.</p> <p>Now, my assumption is that <code>DbSet</code> is working as a type of a proxy, loading lazily objects only when requested, something the <code>ToList()</code> forces it to.</p> <p>I am concerned though about the performance of all this. Is there a better way of making the count of a <code>DbSet</code>? Am I really enforced to do the <code>ToList()</code> call everywhere?</p> <p>I noticed that DbSet is <strong>not</strong> an <a href="https://msdn.microsoft.com/en-us/library/system.data.entity.dbset%28v=vs.113%29.aspx" rel="nofollow">IEnumerable</a>.</p> <p>UPDATE: I forgot to mention that I have Lazy Loading disabled, and that I am invoking this code without having applied Eager Loading to the <code>Items</code> collection, which probably explains a lot.</p>