Linq Syntax & EF Question

I meant what maybe /u/AngularBeginner phrased better. To expand on it :

The first where (where customer.CustomerID == customerId) retrieves all customers whose CustomerID is customerId (so you have a temporary IEnumerable<Customers>).

With every item of that collection, you create a new enumeration of anonymous objects that will be defined like this by the compiler (more or less) :

public class _anon_1 
{
     public Customers customer { get;set; }
     public IEnumerable<_anon_2> Servers { get;set; }
}

Then you do a lot of other stuff, I'll skip that for now.

So now, your query object is of type IEnumerable<_anon_1>. With this collection, you cast it to an IEnumerable<_anon_1> (which it was already), then select a new enumeration (of type IEnumerable<Customers>), and finally take the first of that collection, throwing the Servers property to the garbage. Remember the other stuff I skipped ? That's because it's not used.

If you want to prove this to yourself, run your query with a customer that has enabled and disabled servers. Look at this customer.Servers enumeration, and you will see that you have both enabled AND not enabled servers in it.

That's why I was saying that your code and your question differs.

If what you try to achieve is to get the single customer with matching id, with a Server collection containing only the servers that are enabled, you have different options depending on your use cases (that we don't have) :

  • return the sole customer and only filter the servers on use/display (which would probably be what I'd do in most if not all cases)
  • if the lists are just for display, not update, you could do something along var c = dbContext.Customers.FirstOrDefault(x => x.CustomerId == customerId); if(c == null) { return new Customers(); } // btw, this drives me crazy in your code c.Servers = c.Servers.Include("Notes").Where(s => s.IsEnabled); return c;
  • introduce a real class instead of the anon class and returns it instead, the use its Servers property instead of customer.Servers (which seems error prone)
/r/csharp Thread Parent