views:

170

answers:

2

I have the following query in LINQ. "Symbol" doesn't exist, and the query is null, but I got an error, of casting and the program crashes.

decimal x = from cie in m_entities.Cie
            where cie.symbol.Equals(Symbol)
            select cie.cie_id;

Or can I have a null in x?

+5  A: 

I don't think x will ever be null -- you'll just get an empty IQueryable<T> (or is it IEnumrable<T>?), where T is the datatype of cie_id.

The casting error is because you're attempting to cast the collection to a decimal.

Jay
I see no cast in the code...
dtb
...so you can wrap the query in `(...)` and then call `.FirstOrDefault()` to return the lone result or `0`.
Jay
The cast is implicit in that the query returns a collection, but `x` is being declared as a `decimal`. If `x` were declared with `var` there would be no `InvalidCastException`, but `x` would not be a `decimal`, either.
Jay
Shouldn't this produce a "Cannot implicitly convert type 'IEnumerable<decimal>' to 'decimal'" error at compile-time?
dtb
Yes, and I assume that it does, but that the question is unclear.
Jay
+1  A: 

Assuming that cie_id is a decimal, then try this:

decimal x = (from cie in m_entities.Cie
                     where cie.symbol.Equals(Symbol)
                     select cie.cie_id).FirstOrDefault()

Your current code tries to assign IEnumerable<decimal> to decimal, which won't work. FirstOrDefault will select the first match, if any, otherwise 0.

If you know there will be either 1 or 0 matches, you could consider SingleOrDefault instead of FirstOrDefault.

Dave Gibb