Shlomo Katz
Shlomo Katz

Reputation: 87

LinqtoSql using .first() with asp.net gridview

I am using entity framework with the following linq query

 IQueryable<Order_Details> query = (from ord in ctx1.Order_Details
                             where ord.OrderID == 1
                             select ord).ToArray();

   gv1.DataSource = query;
   gv1.DataBind();

I get a result ok, return a row with orderId of 1
When I use the following,

var query = (from ord in ctx1.Order_Details
             where ord.OrderID == 1
            select ord).First() as IQueryable<Order_Details>;

gv1.DataSource = query;
gv1.DataBind();

I don't recive any results in the gridview

Upvotes: 0

Views: 261

Answers (2)

Brian Mains
Brian Mains

Reputation: 50728

First() returns the Order_Detail record itself, not a collection/array, and therefore is not IQueryable; so using as IQueryable<Order_Details> will return null because it can't be cast. Casting to IQueryable<> can only work for an enumerable of some sort.

If you have to use First, bind to the gridview like this:

var query = (from ord in ctx1.Order_Details
             where ord.OrderID == 1
            select ord).First();

gv1.DataSource = new[] { query };
gv1.DataBind();

Upvotes: 1

Adam Rackis
Adam Rackis

Reputation: 83366

You're trying to cast a single Order_Details object to IQueryable<Order_Details>

Since that's not a valid cast, null is being returned, and your grid is not showing any results.

Your GridView is expecting an IEnumerable, so your original code was correct. Why did you try to change it?

Upvotes: 0

Related Questions