开发者

Querying a Single Column with LINQ

I want to fetch array of values of a single column in a table, for example, I have a table named Customer(ID,Name), and want to fetch ids of all customers. my query in LINQ is:

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

The answer of this query is correct, but I ran SQL Server Profiler, and saw the query which was like this:

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

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

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

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

Thank you.

UPDATE: i have a function for doing this, and this function causes that 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开发者_如何学JAVA like this:

var ids = DBMH.GetSingleColumn<Customer, int>(null, c => c.ID);


If you only select the fields that you need, it will narrow the scope of the resulting SQL query. Try this:

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


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();
   }
  }

That's the way you should do.


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 Func instances instead of Expression instances, you were using Enumerable.Where and Enumerable.Select instead of Queryable.Where and Queryable.Select. That causes local resolution instead of database-side resolution.

  • Enumerable.Select
  • Queryable.Select
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜