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 is like this:
SELECT
[Extent1].[ID] AS [ID],
[Extent1].[CAMPO] AS [CAMPO]
FROM [esquemateste].[TABELA] AS [Extent1]
WHERE [Extent1].[ID] IN (cast(1 as bigint))
Other than SELECT
that actually only filters the columns that will return:
db.TABELA.Select(p=> p.ID ).ToList();
Will generate the following SQL:
SELECT
[Extent1].[ID] AS [ID]
FROM [esquemateste].[TABELA] AS [Extent1]
SUMMING UP
Your first case it will take ALL records from the table, but it will only return the ID column.
Your second case will return all table columns where the id
exists in a collection of Ids.(Where(p => ids.Contains(p.ID))
)
IMPROVING
If I understand correctly what you are doing is to get the details of the products registered on a budget. Surely you are going the right way to join the two, going only once in the database is always (99.9% of the time) better than going twice.
You can do it this way:
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();
That way you make a join
of the two tables by the same ID being picked up in its first query and used in the second.
UPDATING
Correcting a question in the reply according to the @Tobymosque comment. The implementation of the question really does not go twice, while making my reply I took into account the use of the .ToList()
that I put in the first SQL made by me, after that I did not turn attention to the question that the implementation of the question does not have that .ToList()
If the join
(I put in the answer) or in
(that is in question) the performance is the same.
The performance gain would be only if you go twice in the database what would it be like to do this here: (which is different from what is being asked 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 trips to the database because when running the .ToList()
it will execute the query.
Regarding the first, you don’t know what the
Contains
does? It seems to me that you know how to use it. So I don’t know what the doubt is. The second one depends on the context, but it seems that you have nothing to do.– Maniero
I’m confused about
Contains
, for me would bep.Contains
, ie products contain something. So I would like to understandContains
in this context. @bigown– rubStackOverflow