简体   繁体   中英

run time error while converting string to int in entity framework 4.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 ?

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.

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.

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)

)

eg

int from;
int h;
bool fromres= Int32.TryParse(ddlHeightFrom.SelectedValue, out from);
bool hres= Int32.TryParse(p.Height, out h);
...

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM