r/csharp • • 1d ago

EF core linq query syntax vs method.

Looking at the query vs method and can not decide which one is more acceptable.

For some un-explained reason i shudder when i see "from q in _db.Queues" in C#. But at the same time some things looks much less intuitive when written as methods.

2 queries bellow produce same result but i am not sure which way to stick with, so please vote #1 or #2. Or please correct #2 for me if there is another way of writing it.

#2 looks more complicated and i actually can not easily tell what resulting query will be. Will there be some unnecessary allocation for new {q,w} just to discard it since i only need queue object but had to pull webSite object to get isActvie into Where method.

1. await (from q in _db.Queues
                           join w in _db.WebSites on q.webSiteId equals w.id
                           where q.publicKey == queueKey && q.isActive && w.isActive
                           select q).FirstOrDefaultAsync();

2. await _db.Queues.Join(_db.WebSites, x => x.webSiteId, y => y.id, (q, w) => new { q, w }).
    Where(x => x.q.publicKey == queueKey && x.q.isActive && x.w.isActive)
    .Select(x => x.q).FirstOrDefaultAsync();
5 Upvotes

28 comments sorted by

18

u/dgm9704 1d ago

My answer might be frustrating, but here goes. #2 method syntax. And if the code starts looking messy and complicated, then you’re either doing wrong things with the data, or the data is the wrong shape. Fix your logic, break the logic down into cleaner chunks, fix your tables, fix your indexes, create views that match the business logic, etc

1

u/gevorgter 1d ago

I am actually with you, my only frustration is with the (q,w)=>new {q,w}

Although it does not result in un-necessary allocation of new object it still rubs me the wrong way. But sql syntax in my C# code irks me more.

4

u/qrzychu69 1d ago

You know that there is no object involved, right?

IQueryable is translated to SQL, and it's all executed in the database

That's the cool magic bit that makes it amazing

0

u/binarycow 1d ago

Unless you're using those methods on IEnumerable.

1

u/qrzychu69 1d ago

Yeah, but this is a db call

1

u/binarycow 1d ago

That doesn't mean it still uses IQueryable.

Anything the query provider can't convert to SQL is going to fall back to IEnumerable. It will extract what it can from the database, then run the rest of the LINQ via LINQ to Objects (IEnumerable)

3

u/qrzychu69 1d ago

On newer EF core that crashes at runtime and you have to explicitly call '.AsEnunerable()' - there is no implicit fallback

Still, int he case above, it's all db

-1

u/binarycow 1d ago

That assumes EF. There are other query providers.

5

u/qrzychu69 1d ago

What's your point dude.

The title says 'ef'. The query is super easy, nothing that cannot be translated.

Why are you trying to prove some edge case?

0

u/binarycow 1d ago

My only point is that you can't assume that(q,w)=>new {q,w} does not allocate an object, simply because you're using IQueryable. It doesn't, in this case.

→ More replies

4

u/apocolypticbosmer 1d ago

I strongly dislike query syntax, and prefer the LINQ style.

2

u/bigtoaster64 1d ago

Same, I find it very unreadable compared to the method syntax which is very simple : input, output, next call, input, output, next call, etc.

7

u/soundman32 1d ago edited 1d ago

FFS sort out your models.  If you have to use explicitly use join in your query, it's already broken.  EF will work out the required joins if your navigation properties match the DB schema FKs

3

u/Frequent_Field_6894 1d ago

Mr boyce and codd turning in their graves….

0

u/[deleted] 1d ago

[deleted] — view deleted comment

5

u/Disastrous_Fill_5566 1d ago

If you've created your models correctly, then navigation properties means you won't have to explicitly join in the query, but the generated SQL can still have plenty of joins.

0

u/[deleted] 1d ago

[deleted] — view deleted comment

2

u/Disastrous_Fill_5566 1d ago

If you're projecting just the columns you need for read-only purposes then you don't need Include at all. You only need Include if you're planning to mutate state on a referenced entity. If you feel the need to add multiple Includes, that's a sign something may be wrong.

6

u/soundman32 1d ago

If your models have correct navigation properties (based on foreign keys) then EF works out the joins required for whatever query you make, automatically.  There is no need to explicitly write them in each query (one of the 'bug bears' highlighted by OPs question).   Manually specifying a join in linq, whilst it works, is generally a code smell. 

-3

u/WetSound 1d ago

It sounds like you never wrote real code

4

u/Kant8 1d ago

It sounds like you never properly configured your entities or db in general

1

u/soundman32 1d ago

Well, I've been paid for it since 1987, so I'd say you dont have a fucking clue what you are talking about.

0

u/WetSound 1d ago edited 1d ago

That doesn't mean it's good or solves complex problems

2

u/pixxelkick 1d ago

The fluent api (latter) is idiomatic, query syntax is oldschool and backwars supported.

EXCEPT

When you have to manually do a join (rare but it happens), the query syntax is way easier to read and maintain imo.

So if I need to do joins, Ill do those at tge start of my query in query syntax, wrap it in a (....) and then swap to fluent api after

2

u/wubalubadubdub55 1d ago

Love the Query syntax.

It looks so simple and readable.

2

u/Merry-Lane 18h ago

Stupid question but why do you have to write joins manually? Can’t you just create relationships in the entities?

Your LINQ query would just end up being something like:

await _db.Queues
.Where( q=> q.publicKey == queueKey && q.IsActive)
.Select( q => new() { Queue= q, Website = q.Websites
.Where(w => w.IsActive).First() })
.FirstOrDefaultAsync();

Or it can actually be improved by going the other way, if a website has zero or one queue.

Without knowing exactly what you are doing and why, I can but approximate but I’m pretty sure you can write better queries

3

u/buzzon 1d ago

Always functional form . But also use .Include instead of join.

3

u/Agitated-Display6382 1d ago

Don't you have a navigation property between the two entities? If so, you can write:

_db.Queues

.Where(q => q.publicKey == queueKey && q.isActive)

.Where(q => q.WebSites.Any(s => s.isActive))

.FirstOrDefaultAsync()

1

u/smartcave 14h ago

Here's the reality. This isn't an opinion question. The C# spec makes quite clear that linq query syntax is simply syntactic sugar for methods with signatures matching some explicitly defined conventions. More than 90% of the people reading this comment didn't already know that. So, the necessary answer is the explicit method call syntax because it is the least ambiguous.