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/