tags:

views:

111

answers:

4

The following query complains that the int conversion is not supported.

var list = from d in data
           where d.Id == (int)GridView1.DataKeys[0].Value
           select d;

It complains on the (int)GridView1.SelectedInex line telling me that the Int conversion is not supported. I also tried Convert.ToInt32, but that did not work either.

Is this logic that has to be calculated before such as above the linq query or is there a special way to do it and if not, why does it not support it?

A: 

I'm guessing here, but try:

where d.Id == (int)(GridView1.DataKeys[0].Value);

in case it's trying to cast the GridView.

(edit: fixed code - see comment on question)

This answer is wrong!

Lucas Jones
That's not the case, this code is equivalent to the code in the question
Sander Rijken
OK. No problem - just a guess! :)
Lucas Jones
Thanks for trying anyways.
Xaisoft
+7  A: 

Why not try and parse the value to an integer before hand, it's not needed in the query.

Int id;
if (Int32.TryParse(ridView1.DataKeys[0].Value.ToString(), out id))
{
    var list = from d in data
               where d.Id == id
               select d;
}
Michael G
= needs to be == otherwise the expression will fail as it is not boolean.
envalid
@envalid: fixed, sorry, copy paste oversight :)
Michael G
If I had had any upvotes left today, I'd +1 this. :)
daft
+1  A: 

I assume the semicolon after the where line is a typo?

Pull the cast outside the linq query, it's trying to generate SQL for the cast operation, which isn't supported

int id = (int)GridView1.DataKeys[0].Value;
var list = from d in data
           where d.Id = id
           select d;
Sander Rijken
Yeah sorry, I removed the semi-colon. This is what I meant about doing the logic above the query first and then using the calculated value in the where clause.
Xaisoft
So what you are saying is that Linq does not support the SQL CAST expression? Do you know why?
Xaisoft
it doesn't have to do with SQL CAST, the Linq provider translates the Linq query to SQL by parsing the expression tree. It can't do that when an operation in the tree cannot be translated to SQL
Sander Rijken
Shouldn't the CAST in the linq query generate a SQL cast that can be generated translated to SQL.
Xaisoft
No, it cannot be mapped. .Cast<T> and .OfType<T> work though, but that's on IEnumerable/IQueryable
Sander Rijken
A: 

you are casting, not converting.

int.Parse( GridView1.DataKeys[0].Value )

would be converting.

GridView1.DataKeys[0].Value returns an object which may or may not be an int.

Muad'Dib
casting or not casting isn't what's causing that message
Sander Rijken