实体框架/ LINQ的EX pression从字符串转换为int [英] Entity Framework/Linq EXpression converting from string to int

查看:176
本文介绍了实体框架/ LINQ的EX pression从字符串转换为int的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个防爆pression像这样:

I have an Expression like so:

var values = Enumerable.Range(1,2);

return message => message.Properties.Any(
    p => p.Key == name 
    && int.Parse(p.Value) >= values[0] 
    && int.Parse(p.Value) <= values[1]);

这个编译很好,但是当它击中该数据库抛出异常LINQ到实体不能识别方法的Int32解析(System.String)的方法,而这种方法不能被翻译成店内EX pression

This compiles fine but when it hits the database it throws the exception 'LINQ to Entities does not recognize the method 'Int32 Parse(System.String)' method, and this method cannot be translated into a store expression '

如果我不这样做了解析,并具有值是的String [] ,我不能再使用&GT; = &LT;。= 运营商对字符串

If I don't do the parse and have values be a string[] I can't then use the >= and <= operators on strings.

p.Value 是持有不同价值观,但在这种情况下,它是一个字符串 INT

p.Value is a string which holds various values but in this case it is int

有没有一种方法可以让我查询数据库做这样的说法?

Is there a way I can query the database to do this sort of between statement?

推荐答案

正如其他人的意见,那你不必解析这个值的事实应该是,你应该使用不同的数据红旗输入您的数据库中。

As pointed out by others in the comments, the fact that you're having to parse this value should be a red flag that you should be using a different data type in your database.

幸运的是,有一种变通方法通过强制查询被LINQ到对象,而不是LINQ到实体执行。不幸的是,这意味着潜在的读取大量数据到存储器

Fortunately, there is a workaround by forcing the query to be executed by LINQ to Objects rather than LINQ to Entities. Unfortunately, it means potentially reading a large amount of data into memory

修改

,在值列中的值ins't保证是一个数字。因此,你必须尝试的价值转换成一个数字,然后搬运东西的基础上的转换失败/成功的:

Based on your other comments, the value in the Value column ins't guaranteed to be a number. Therefore, you'll have to try converting the value to a number and then handling things based on the failure/success of that conversion:

return message
       .Properties
       .AsEnumerable()
       .Any(p => 
            {
                var val = 0;
                if(int.TryParse(p.Value, out val))
                {
                    return p.Key == name &&
                           val >= values[0] &&
                           val <= values[1])
                }
                else
                {
                    return false;
                }
           );

编辑2

您也许真的能逃脱这个数据库中。我不知道这是否会工作或不适合你,但给它一个镜头:

You might actually be able to get away with this in the database. I'm not sure if this will work or not for you but give it a shot:

return message.Properties
              .Where(p => p.Key == name && SqlFunctions.IsNumeric(p.Value) > 0)
              .Any(p => Convert.ToInt32(p.Value) >= values[0] &&
                        Convert.ToInt32(p.Value) <= values[1]);

这篇关于实体框架/ LINQ的EX pression从字符串转换为int的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆