views:

221

answers:

2

Here's the code:

string name = "myName";

int id = (int)_myDB.ThingTable.Where(thing => thing.ThingName == name)
                     .Select(thing => thing.ThingId);

I have an error saying System.Linq.IQueryable cannot be converted to int (I'm assuming it's so that I don't end up with a case where no rows are found- no id is returned)

First, how can I cast it to an int?

Second, what gets returned if no record with a ThingName == name exists?

Thanks,
Matt

+2  A: 

You need a query expression that returns a scalar. Something like:

myCollection.Where(c => c.X > 0).FirstOrDefault();

In your example it would be:

int id = (int)_myDB.ThingTable.Where(thing => thing.ThingName == name)
                 .Select(thing => thing.ThingId).FirstOrDefault();

If no row is returned, the default value of the scalar is returned (generally zero in the case of a non-nullable number).

Robert Harvey
A: 

Try using FirstOrDefault() on queries such as that. It will return the default value for the selection if nothing is returned. 0 for numbers, null for objects.

Andrew Siemer