prers
prers

Reputation: 99

Cannot convert type 'System.Linq.IQueryable<double?>' to 'float'

I have a table named InventoryItem which consists of columns ItemDescription and Item BalanceQty.I want to fetch the BalanceQty of the ItemName selected in a comboBox.For this,I created a method in my Data Access Layer And passed the string parameter representing the string value of ItemDescription to this method.This has been implemented using Entity Framework.This is how my code looks:

public float GetAvailableQty(string itemName)
{
    float availableQty =(from table in context.InventoryItem
    where table.ItemDescription == itemName
    select table.BalanceQuantity);

    return availableQty;
}    

But it is giving me the following error-

Cannot convert type 'System.Linq.IQueryable' to 'float'

Where am I going wrong?

Upvotes: 1

Views: 4042

Answers (2)

Noctis
Noctis

Reputation: 11773

Because your Linq returns an Iqueryable ...

Lets assume you have 3 rows with with an item with 3 different quatities (silly, i know, but think about other things that can have multiple values per item, like colors for a paint). Your linq will return the three quantities, and you're assuming it's a number

You could use First or FirstOrDefault to fetch the first item, or the default value for that object.

In your case, it shouldn't matter, but you should realize how Linq works and what it returns ...


Another example:

let's assume : List numbers = {1,2,3,4,5,6} (let's assume they are ints). and you do : var small_numbers = numbers.Where(x => x<4) What you get is something you can then query like: foreach (var small in small_numbers) {...}). The result is not an int.

You could take the first, last, and indeed, that would be an int. But what you get is a collection. so, even if you do: var one_result = numbers.Where(x => x<2), one_result is not an int.

Upvotes: 1

LINQ2Vodka
LINQ2Vodka

Reputation: 3036

Probably you need this:

double availableQty =(from table in context.InventoryItem
    where table.ItemDescription == itemName
    select table.BalanceQuantity).Sum();

IQueriable returns an expression tree. The result of query like this is a rows set, and it can be materialized to IEnumerate by using of ToList() or implicitly by assigning to IEnumerable. But anyway it will be rows set, not a single value. If you sure the query returns the single one then use .Single() or SingleOrDefault. See other extension methods for IQueriable.

Otherwise, if you need an array then assign result to some IEnumerable variable.

Upvotes: 3

Related Questions