Single Column Query with LINQ

I want to get an array of values ​​of one column in a table, for example, I have a table called Customer (ID, Name), and you want to get the identifiers of all customers. my query in LINQ:

var ids = db.Customers.Select(c=>c.ID).ToList();

The answer to this question is correct, but I ran SQL Server Profiler and saw a query that looked something like this:

SELECT [t0].[ID], [t0].[Name] FROM [dbo].[Customer] AS [t0]

I realized that LINQ selects all the columns and then creates an integer array of ID fields.

How can I write a LINQ query that generates this query in SQL Server:

SELECT [t0].[ID] FROM [dbo].[Customer] AS [t0]

Thank.

UPDATE: I have a function for this, and this function calls this result:

public static List<TResult> GetSingleColumn<T, TResult>(Func<T, bool> predicate, Func<T, TResult> select) where T : class
{
    using (var db = new DBModelDataContext())
    {
        var q = db.GetTable<T>().AsQueryable();
        if (predicate != null)
            q = q.Where(predicate).AsQueryable();
        return q.Select(select).ToList();
    }
}

and use it as follows:

var ids = DBMH.GetSingleColumn<Customer, int>(null, c => c.ID);
+3
source share
3 answers
public static List<TResult> GetSingleColumn<T, TResult>(
   Expression<Func<T, bool>> predicate,
   Expression<Func<T, TResult>> select) where T : class
  {
   using (var db = GetData())
   {
    var q = db.GetTable<T>().AsQueryable();
    if (predicate != null)
     q = q.Where(predicate).AsQueryable();
    var q2 = q.Select(select);
    return q2.ToList();
   }
  }

What you have to do.

+2

, , SQL-. :

var ids = from customer in db.Customers
          select customer.ID;
+4

Fix'd!

public static List<TResult> GetSingleColumn<T, TResult>
(
  Expression<Func<T, bool>> predicate,
  Expression<Func<T, TResult>> select) where T : class 
{ 

Since you used instances Funcinstead of instances Expression, you used Enumerable.Whereboth Enumerable.Selectinstead of Queryable.Whereand Queryable.Select. This results in local permission, not the database side of the permission.

+1
source

Source: https://habr.com/ru/post/1747130/


All Articles