First let's understand the SQL that each of them generates:
The contains
is a WHERE id in ()
. When executing a query like this:
db.TABELA.Where(p => ids.Contains(p.ID)).ToList();
The generated SQL looks like this:
SELECT
[Extent1].[ID] AS [ID],
[Extent1].[CAMPO] AS [CAMPO]
FROM [esquemateste].[TABELA] AS [Extent1]
WHERE [Extent1].[ID] IN (cast(1 as bigint))
Unlike the SELECT
that actually only filters the columns that will return:
db.TABELA.Select(p=> p.ID ).ToList();
It will generate the following SQL:
SELECT
[Extent1].[ID] AS [ID]
FROM [esquemateste].[TABELA] AS [Extent1]
SUMMARY
Your first case will fetch ALL records from the table, but will only return the ID column.
Your second case will return all the columns of the table where id
exists in a collection of IDs ( Where(p => ids.Contains(p.ID))
)
IMPROVING
If I understood correctly what you are doing is to get the details of the products registered on a budget. Surely you are going to the right way to join the two, go only once in the database is always (99.9% of the time) rather than go twice.
You can do this as follows:
var prods = (from io in db.itensOrcamento
join p in db.protudo on p.ID equals io.ID
where io.ID_DA_VENDA = XXX
select p).ToList();
This way you make a join
of the two tables by the same ID being picked up in your first query and used in the second one.
UPDATE
Correcting an issue in response to @TobyMosque's comment. The implementation of the question really does not go twice, in making my answer I took into consideration the use of .ToList()
that I put in the first SQL done by me, after that I did not return to the attention the question that the implementation of the question does not have this .ToList()
If you use the join
(which I put in the answer) or the in
(which is in the question) the performance is the same.
The performance gain would only be if you go twice in the database what would be doing it here: (which is different from what is being done in the question)
var t = db.TABELA.Where(p => ids.Contains(p.ID)).ToList();
var produtos = Produtos.Where(p => p.id = t.id).ToList();
This generates two database hits because when running .ToList()
it will execute the query.