简体   繁体   English

Linq 表达式中的 Int.Parse

[英]Int.Parse in Linq Expression

I have the following LINQ expression.我有以下 LINQ 表达式。 I want calculate the sum of numeric values in an nvarchar field.我想计算nvarchar字段中数值的总和。 I'm using following code to do this, but I get an error when I try to run this.我正在使用以下代码来执行此操作,但是当我尝试运行它时出现错误。

var m = new MaterialModelContainer();

var list = 
    (from x in
        (
            from inv in m.INVs
            join l in m.LIBs on inv.MESC equals l.MESC
            join o in m.OUTs on inv.MESC equals o.MESC
            join t in m.TRANs on inv.MESC equals t.MESC
            where t.TYPE == "60"
            select new
            {
                l.MESC,
                l.LINE_NO,
                l.UNIT_LINE,
                Description = l.DES + " " + l.PART_NO,
                inv.NEW_QTY,
                o.PJ,
                o.DATE,
                o.QTY,
                o.QTY_REC,
                TranQty = t.QTY,
                tranDate = t.DATE
            }
        )
        group x by
            new
            {
                x.MESC,
                x.LINE_NO,
                x.UNIT_LINE,
                x.Description,
                x.NEW_QTY,
                x.PJ,
                x.DATE,
                x.QTY,
                x.QTY_REC
            }
        into g
        select new
        {
            QTY_Consum_1 = g.Where(c => int.Parse(c.tranDate) >= cuDate && int.Parse(c.tranDate) <= endDate).Sum(d => int.Parse(d.TranQty))
        }
    ).ToList();

Error Description:错误描述:

LINQ to Entities does not recognize the method 'Int32 Parse(System.String)' method, and this method cannot be translated into a store expression LINQ to Entities 无法识别 'Int32 Parse(System.String)' 方法,并且此方法无法转换为存储表达式

How can I solve this problem and write this code better than this?我怎样才能解决这个问题并编写比这更好的代码?

I changed the code to this:我将代码更改为:

select new
{
    QTY_Consum_1 = g.Where(c => SqlFunctions.StringConvert(c.tranDate) >= cuDate && SqlFunctions.StringConvert(c.tranDate) <= endDate).Sum(d => SqlFunctions.StringConvert(d.TranQty)),
   g.Key.MESC
}
).ToList();

but got this error:但出现此错误:在此处输入图像描述

EF 5: EF 5:

Instead of int.Pasrse use Convert.ToInt32 . 而不是int.Pasrse使用Convert.ToInt32 Entity Framework will generate proper CAST functions in SQL. 实体框架将在SQL中生成适当的CAST函数。

EF 6: EF 6:

Short answer: 简短回答:

youEntity.Where(c=>SqlFunctions.StringConvert((decimal?)c.INTFIELD).Trim() == STRINGVALUE)

Long answer: 答案很长:

in EF 6 you have to convert numeric value to string with SqlFunctions.StringConvert . 在EF 6中,您必须使用SqlFunctions.StringConvert将数值转换为字符串。 but it has a problem. 但它有一个问题。 It will add unnecessary spaces to the result. 它会为结果添加不必要的空格。 so the comparison will fail. 所以比较会失败。 That's why I have put Trim() there. 这就是我把Trim()放在那里的原因。 I have tested it with EF 6.1.1. 我用EF 6.1.1进行了测试。

Replace all your int.Parse by SqlFunctions.StringConvert(variable) . SqlFunctions.StringConvert(variable)替换所有的int.Parse There's no function to convert String to Int. 没有将String转换为Int的函数。 You should try to do the inverse and convert your Int to String with StringConvert. 您应该尝试执行反转并使用StringConvert将Int转换为String。

The SqlFunctions utilities will be able to translate the command in SQL command. SqlFunctions实用程序将能够在SQL命令中转换该命令。

Entity Framework can't translate that type of conversion to SQL. 实体框架无法将该类型的转换转换为SQL。

Is there any chance you could alter your data structure to use proper data types such as actual DateTime types? 您是否有可能改变数据结构以使用正确的数据类型,例如实际的DateTime类型? For large data volumes conversions like that will affect performance. 对于大数据量,这样的转换会影响性能。

I would recommend either changing your data model types to avoid these conversions, or if the amount of data will always be small , then get the data first, and later use Linq to Objects. 我建议您更改数据模型类型以避免这些转换,或者如果数据量总是很小 ,则先获取数据,然后再使用Linq to Objects。

In your where clause, you can't call int.Parse . 在你的where子句中,你不能调用int.Parse Entity Framework doesn't know how to convert that to SQL. 实体框架不知道如何将其转换为SQL。 Consider revising your Where . 考虑修改你的Where

You can't use int.parse in where . 你不能在where使用int.parse。 You can rewrite your query like this: 您可以像这样重写您的查询:

var list = (from x in
                (
                    from inv in m.INVs
                    join l in m.LIBs on inv.MESC equals l.MESC
                    join o in m.OUTs on inv.MESC equals o.MESC
                    join t in m.TRANs on inv.MESC equals t.MESC
                    where t.TYPE == "60" && t.QTY!=""
                    select new
                       {
                           l.MESC,
                           l.LINE_NO,
                           l.UNIT_LINE,
                           Description = l.DES + " " + l.PART_NO,
                           inv.NEW_QTY,
                           o.PJ,
                           o.DATE,
                           o.QTY,
                           o.QTY_REC,
                           TranQty = t.QTY,
                           tranDate = t.DATE

                      }
                ).ToList()
            group x by
                new
                    {
                        x.MESC,
                        x.LINE_NO,
                        x.UNIT_LINE,
                        x.Description,
                        x.NEW_QTY,
                        x.PJ,
                        x.DATE,
                        x.QTY,
                        x.QTY_REC
                    }
            into g
            select new
                {
                    QTY_Consum_1 = g.Where(c => int.Parse(c.tranDate) >= cuDate && int.Parse(c.tranDate) <= endDate).Sum(d => int.Parse(d.TranQty)),
                    g.Key.MESC
                }
           ).ToList();

Call .ToList() method, then use int.Parse(variable) . 调用.ToList()方法,然后使用int.Parse(variable)

Have a nice day. 祝你今天愉快。

If you need a lot, I recommend CodeFirstStoreFunctions .如果您需要很多,我推荐CodeFirstStoreFunctions

Step0 -> CodeFirstStoreFunctions nuget install Step0 -> CodeFirstStoreFunctions nuget 安装

Step1-> Create a simple sql scalar functions Step1-> 创建一个简单的 sql 标量函数

 CREATE FUNCTION [dbo].[ToInt32](@Value VARCHAR(255)) 
 RETURNS INT
 AS
 BEGIN
 RETURN CONVERT(INT, (CASE WHEN ISNUMERIC(@Value) = 1 THEN @Value ELSE 
 '0' END))
 END

Step2 -> add in OnModelCreating Step2 -> 添加OnModelCreating

mb.Conventions.Add(new FunctionsConvention("dbo", typeof(SqlHelper)));

Step3 -> build in the SqlHelper class Step3 -> 构建 SqlHelper 类

[DbFunction("CodeFirstDatabaseSchema", "ToInt32")]
public static int ToInt32(string value) => throw new NotSupportedException();

Result ->结果 -> 在此处输入图像描述

When you need to make sure a CLR method can be used in LINQ to Entities you'd better consult this source: https://msdn.microsoft.com/en-us/library/vstudio/dd456828(v=vs.100).aspx . 当你需要确保在LINQ to Entities中使用CLR方法时,你最好咨询这个来源: https//msdn.microsoft.com/en-us/library/vstudio/dd456828(v = vs.100) .aspx

Not a fast reading, it'd take time, but here's the answer to your question (and many more like it). 这不是一个快速的阅读,它需要时间,但这是你的问题的答案(更多的是它)。

There is a badly built database, which I cannot edit, but have to use it. 有一个构建严重的数据库,我无法编辑,但必须使用它。

I use this in Linq-To-Sql and it works. 我在Linq-To-Sql中使用它,它可以工作。

First cast the string to object, then cast it to int. 首先将字符串强制转换为object,然后将其强制转换为int。

 from s in db.Students
 select new
 {
     s.Name,
     s.Surname,
     Birthday = new DateTime((int)(object)(s.dateStr.Substring(0, 4)),
                             (int)(object)(s.dateStr.Substring(4, 2)),
                             (int)(object)(s.dateStr.Substring(6, 2))),
 }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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