0
protected void GetFinalResult(IQueryable<clsProfileData> result)
{
    if (ddlHeightFrom.SelectedValue != "0" && ddlHeightTo.SelectedValue != "0")
    {
        int from = Convert.ToInt32(ddlHeightFrom.SelectedValue);      
        result = result.Where(p => Convert.ToInt32(p.Height) > from);
    }
}

I am using Entity Framework 4.0 and in above method p.Height is error causing conversion(string to int). is there any way to handle this ?

Rob
  • 4,927
  • 12
  • 49
  • 54
Sarang Amrutkar
  • 873
  • 1
  • 7
  • 10

3 Answers3

1

One advice: store the heights as numbers in the database, if you can. EF (currently) has no built-in functions to easily convert strings to numbers. Nor do EntityFunctions* or SqlFunctions help you.

Storing numbers will not only make the querying much easier, but it will also enable you to write sargable queries. The Where with a conversion, as you've got now, disables any index on your column.

If you can't change the database, you may be able to use a work-around: you could store the numbers with leading zeros to make sure they all have the same lenght. Then you could use string comparison, because 00002 comes before 00010, whereas 2 comes after 10 when sorting. Doing so, you can use String.Compare in your linq statement, which translates to < or > in sql.

See also: https://stackoverflow.com/a/10521557/861716

*DbFunctions as of Entity Framework 6.

Community
  • 1
  • 1
Gert Arnold
  • 105,341
  • 31
  • 202
  • 291
1

I had an error in converting a string to an Int32. I couldn't find anywhere in the XML datadescriptions where the field was an Int32. In the end the stored proc was returning that field as an int, not a string. It's odd that the error messaged complained that it couldn't cast the data, in the other direction.

Markus
  • 1,020
  • 14
  • 18
0

Try parsing for validity first:

http://msdn.microsoft.com/en-uk/library/f02979c7.aspx

(probably at the point at which you do this, as well:

Convert.ToInt32(ddlHeightFrom.SelectedValue)

)

e.g.

int from;
int h;
bool fromres= Int32.TryParse(ddlHeightFrom.SelectedValue, out from);
bool hres= Int32.TryParse(p.Height, out h);
...
davek
  • 22,499
  • 9
  • 75
  • 95
  • Ok i tried this if (ddlHeightFrom.SelectedValue != "0" && ddlHeightTo.SelectedValue != "0") { int from; int height; bool bfrom = Int32.TryParse(ddlHeightFrom.SelectedValue, out from); result = result.Where(p => (Int32.TryParse(p.Height, out height) ? height : 0) > from); } now getting "does not recognize the method 'Boolean TryParse(System.String, Int32 ByRef)' method" error. I want Int32.TryParse(p.Height, out height) to be parsed in single lambda expression only as i need all results to be parsed in same line of code. – Sarang Amrutkar Jul 19 '12 at 09:53