简体   繁体   中英

What is the difference between these two LINQ Queries and how to correctly optimize them?

I have a Clients table which has the following columns: Id, FirstName, LastName, CurrencyId, Gender.

I want to select the client's Currency that corresponded to Id 10 so I am doing something like this:

var currencyId = Db.Clients.FirstOrDefault(c=>c.Id == 10)?.CurrencyId;

Does this line bring all properties from Db and selects the currency in the code or it executes something like this in the database:

SELECT currencyId FROM Client WHERE ID = 10

Or I should write the linq like this:

var currencyId = Db.Clients.Where(c=>c.Id == 10).Select(c=>c.CurrnecyId).FirstOrDefault();

What's the difference between the two queries? And what is the correct way to translate the above SQL query into a linq query?

Looked into it myself cause I found the anwser from most people questionable. I expect the FirstOrDefault to materialize the result (you also see from the type that you are not longer working with a query object), so that would mean it queries for all properties.

Unlike the 2nd query where you are still working with a query when filtering the property you like, thus dependent on the implementation it could be used for filtering properties and selecting specific fields.

The following is an example of the queries generated using EF for two similar queries, where it shows both generating different queries: https://dotnetfiddle.net/5aFJAZ

In your first example, var currencyId = Db.Clients.FirstOrDefault(c=>c.Id == 10)?.CurrencyId; the query selects the entire object to memory and then returns the Id property from that in memory object. As a result it needs to do something like the following SQL: SELECT * FROM Clients WHERE Id = 10 . I understand I'm not using a parameter here and EF does spell out every column. However the key to understand here is that by returning more columns than you need, you potentially are setting up a performance concern because a covering index on Id and CurrencyId would not be used.

Your second LINQ query would use a SQL statement like SELECT CurrencyId FROM Clients Where Id = 10 which would take advantage of your indexes assuming you have an index covering these columns.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM