How to select a single column with Entity Framework?


Is there a way to get the entire contents of a single column using Entity Framework 4? The same like this SQL Query:

SELECT Name FROM MyTable WHERE UserId = 1;

This question is tagged with c# entity-framework

~ Asked on 2012-01-29 16:13:59

The Best Answer is


You can use LINQ's .Select() to do that. In your case it would go something like:

string Name = yourDbContext
  .Where(u => u.UserId == 1)
  .Select(u => u.Name)
  .SingleOrDefault(); // This is what actually executes the request and return a response

If you are expecting more than one entry in response, you can use .ToList() instead, to execute the request. Something like this, to get the Name of everyone with age 30:

string[] Names = yourDbContext
  .Where(u => u.Age == 30)
  .Select(u => u.Name)

~ Answered on 2012-01-29 16:28:47


I'm a complete noob on Entity but this is how I would do it in theory...

var name = yourDbContext.MyTable.Find(1).Name;

If It's A Primary Key.

-- OR --

var name = yourDbContext.MyTable.SingleOrDefault(mytable => mytable.UserId == 1).Name;

-- OR --

For whole Column:

var names = yourDbContext.MyTable
.Where(mytable => mytable.UserId == 1)
.Select(column => column.Name); //You can '.ToList();' this....

But "oh Geez Rick, What do I know..."

~ Answered on 2017-09-29 12:47:32

Most Viewed Questions: