[英]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). 我正在使用Entity Framework 4.0和上面的方法p.Height
是导致转换的错误(字符串为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. EF(当前)没有内置函数可以轻松地将字符串转换为数字。 Nor do EntityFunctions * or SqlFunctions help you. EntityFunctions *或SqlFunctions也不会帮助你。
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. 在Where
有一个转换,你现在得到,禁止在您的专栏任何索引。
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. 然后你可以使用字符串比较,因为00002
在00010
之前,而2
在排序之后在10
之后。 Doing so, you can use String.Compare
in your linq statement, which translates to <
or >
in sql. 这样做,你可以在你的linq语句中使用String.Compare
,它在sql中转换为<
或>
。
See also: https://stackoverflow.com/a/10521557/861716 另见: https : //stackoverflow.com/a/10521557/861716
* DbFunctions as of Entity Framework 6. *实体框架6中的DbFunctions 。
I had an error in converting a string to an Int32. 将字符串转换为Int32时出错。 I couldn't find anywhere in the XML datadescriptions where the field was an Int32. 我在XML数据描述中找不到任何字段,其中字段是Int32。 In the end the stored proc was returning that field as an int, not a string. 最后,存储过程将该字段作为int返回,而不是字符串。 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 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);
...
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.