c# - 使用 LINQ 转换为 Int

标签 c# entity-framework linq int type-conversion

LINQ 下面有几个 Convert.ToInt32 方法。但它不起作用。引用网上说是用int.Parse代替convert。还是报错。请告诉我执行此操作的方向。

在下面的查询中,tody 的数据类型是DateTime

var ds = (from a in dbSetInvHeader
          join b in dbSetCustomer on a.BusinessEntityID equals b.Id
          join c in dbSetFinancialInfo on b.Id equals c.Id
          where (a.TotalAmount - a.AppliedAmount - a.ApplyToInvoiceCreditAmount) > 0
                      && DbFunctions.AddDays(a.InvoiceDate, Convert.ToInt32(c.CreditPeriod)) >= tody
          select new OverDueInvoices
                      {
                          CustomerName = b.Name,
                          InvoiceNo = a.InvoiceNo,
                          InvoiceAmount = a.TotalAmount - a.ApplyToInvoiceCreditAmount,
                          DueAmount = (a.TotalAmount - a.AppliedAmount - a.ApplyToInvoiceCreditAmount),
                          CreditAmount = a.ApplyToInvoiceCreditAmount,
                          NoOfDays = Convert.ToInt32(DbFunctions.DiffDays(tody, a.InvoiceDate))
                      }).ToList();

更新:

代码使用 Entity Framework 来解决上面的 LINQ 抛出错误:

当使用 Convert.ToInt32 时:

"LINQ to Entities does not recognize the method 'Int32 ToInt32(System.Decimal)' method, and this method cannot be translated into a store expression."

当使用 int.Parse 时:

"LINQ to Entities does not recognize the method 'Int32 Parse(System.String)' method, and this method cannot be translated into a store expression."

最佳答案

正如@LiviuBoboia 指出的,SQL 对这两个 Convert.ToInt32 都一无所知。和 int.Parse方法和 EF 无法正确地将对此方法的调用转换为 sql。取而代之的是你可以做简单的转换:

NoOfDaysString = (int)DbFunctions.DiffDays(tody, a.InvoiceDate)

此转换将作为 sql 函数转换为 sql CONVERT这应该很好用。

虽然,DbFunctions.DiffDays返回 Nullable<int>int?所以最好避免将其转换为 (int)因为你可以获得InvalidCastException在尝试转换 null 时至 int

关于c# - 使用 LINQ 转换为 Int,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42619452/

相关文章:

c# - 将实时推文流式传输到 my .net 网站

c# - ASP.NET 保存复杂的实体模型

c# - .OrderBy()/.OrderByDescending() 与 .FirstOrDefault()/.First()

Linq 查询给出无效的列名 "xyz"错误

c# - 将命令绑定(bind)到 UserControl 内的 ViewModel

c# - 将字符串转换为十六进制,然后转换为字节数组

c# - 在 C# 中使用 .Show() 方法后,由于循环而导致对话框无法正确显示

c# - 没有 [必需] 的 EF 模型属性不为空

c# - 创建模型时无法使用上下文

c# - LINQ to XML - 根据与另一个 XElement 相比的节点值过滤 XElement?