Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Select only a single column in LINQ

The EntityModel is defined as: Personnel has a link to a Country

When executing this code in LinqPad, I see that the SQL which is generated is not optimized (all fields are returned) in the first query ? What am I missing here or doing wrong ?

Query 1 LINQ

var Country = Countries.FirstOrDefault(o => o.Id == 100000581); var personnelIds = Country.Personnels.Select(p => p.Id).ToArray(); personnelIds.Dump(); 

Query 1 SQL

exec sp_executesql N'SELECT [t0].[Id], [t0].[Version], [t0].[Identifier], [t0].[Name], , [t0].[UpdatedBy] FROM [Personnel] AS [t0] WHERE [t0].[Country_Id] = @p0',N'@p0 bigint',@p0=100000581 



Query 2 LINQ

var Country = Countries.FirstOrDefault(o => o.Id == 100000581); var personnelIds2 = Personnels.Where(p => p.Country == Country).Select(p => p.Id).ToArray(); personnelIds2.Dump(); 

Query 2 SQL

exec sp_executesql N'SELECT [t0].[Id] FROM [Personnel] AS [t0] WHERE [t0].[Country_Id] = @p0',N'@p0 bigint',@p0=100000581 


The database used is SQL Express 2008. And LinqPad version is 4.43.06

like image 446
Stef Heyenrath Avatar asked Mar 28 '13 19:03

Stef Heyenrath


People also ask

How to Select single column in Linq query c#?

Popular Answer FirstOrDefault(o => o.Id == 100000581); var personnelIds = context. Personnels . Where(p => p.Country.Id == 100000581) . Select(p => p.Id) .

How do I select a single column in Entity Framework?

You could use the LINQ select clause and reference the property that relates to your Name column. Show activity on this post. If you're fetching a single item only then, you need use select before your FirstOrDefault()/SingleOrDefault(). And you can use anonymous object of the required properties.

How to get single column value from DataTable in c# using Linq?

var Q1 = (ds. Tables[1]. AsEnumerable() .


1 Answers

//var Country = Countries.FirstOrDefault(o => o.Id == 100000581); var personnelIds = context.Personnels     .Where(p => p.Country.Id == 100000581)     .Select(p => p.Id)     .ToArray();  personnelIds.Dump(); 

Try this, it should be better.

like image 159
AD.Net Avatar answered Oct 01 '22 18:10

AD.Net