Linq Syntax & EF Question

Howdy. I'm working on a project using Entity framework, and having just gotten slightly comfortable with it, i ran into something that at first seemed to be impossible. However i persevered and got through it, however, it looks a lot more difficult than it should be (or perhaps that's just me?):

My Situation:

I have a Customer Table, In this i have a reference to a Servers table (In other words, Servers per customer) In this (servers table) i have a reference to a Notes table as in, Notes per server.

So my query needs to give me a list with both, The customer in question, Their servers, and their servers notes.

That didn't seem to hard once i found the .Include. However, The servers needs to have .IsEnabled set to true

So after an hour of scratching my head, i got to this:

 public Customers GetSpecificCustomerWithEverything(int customerId) { using (var dbContext = new DatabaseEntities()) { dbContext.Configuration.LazyLoadingEnabled = false; var query = from customer in dbContext.Customers where customer.CustomerID == customerId select new { customer, Servers = from server in customer.Servers where server.IsEnabled select new { server, Notes = from notes in server.Notes select notes } }; var firstOrDefault = query.AsEnumerable().Select(x => x.customer).FirstOrDefault(); return firstOrDefault ?? new Customers(); } } 

Question One: Can this be done any easier? Question Two: I've seen a few posts using a 'Linq Method' syntax that usually goes something like .Select(x => x.bla) Is there any benefits to using one, over the other? Readability, to be seems to be far superior in the linq syntax ( the one i used above ). Thoughts?

TL;DR – The above code – Can that be done easier and/or better? — Linq Syntax vs Linq Methods?

Thanks.

by Slackerony via /r/csharp

Leave a Reply