I’m getting the below error in my C#/ASP.NET project for some reason – presumably it’s relating to the SubString part of the query. However, ‘SageJobNo’ and ‘CutOffDate’ are always populated.
Error:
Invalid length parameter passed to the LEFT or SUBSTRING function.
And the code is below:
IEnumerable<CcsVwICATimesheet> Timesheets = (from s in SageDC.CcsVwICATimesheets where s.Contract_Number.Substring(0, s.Contract_Number.IndexOf(" ")) == SageJobNo && s.Timesheet_Date <= CutOffDate select s);
foreach (CcsVwICATimesheet Timesheet in Timesheets)
{
LabourCosts += (double)Timesheet.Cost_Value;
}
EDIT: The error occurs on the ‘foreach’ line
If you don’t have any
' 'in your stringIndexOfwill return -1 and Substring will fail.Edit
You can safeguard by checking if the string contains
" ".If you prefer the ternary operator that could be used as well.
If you use Linq2Objects you can use
s.Contract_Number.Split().First(), but LINQ can not translate that to SQL.