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 ?

1
  • 1
    Why aren't you storing Height as int in the database? Commented Jul 19, 2012 at 8:35

3 Answers 3

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.

Sign up to request clarification or add additional context in comments.

Comments

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.

Comments

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);
...

1 Comment

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.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.