Reputation: 572
Hope everybody is pretty good.
Well, I am getting a weird 'Specified Cast is not valid.' exception in one of my LINQ queries.
The code is as follows:
public string GetFiscalYearID(string fiscalYear)
{
int fYear = Convert.ToInt32(fiscalYear);
DataTable dtFiscalYearID = new DataTable();
dtFiscalYearID = DomainBL.GetDomainDataFromFieldName("FiscalYearId");
**var item = from r in dtFiscalYearID.AsEnumerable()
where r.Field<Int32>("FiscalYearNumber") == fYear
select r.Field<Int32>("FiscalYearId");**//Exception at this line
if (item.ToList().Count> 0)
{
return item.ToList()[0].ToString();
}
else
{
return string.Empty;
}
}
Here, dtFiscalYearID gets a DataTable from the DB which has just 2 columns namely, FiscalYearId and FiscalYearNumber. DataTypes of FiscalYearId and FiscalYearNumber are tinyint and smallint respectively.
When item is expanded, I see the Specified Cast exception, I tried Int16 too, but it too throws me an exception.
Can experts here tell me what might be wrong in the above code? Any pointers or such will be quite appreciated.
Regards Anurag
Upvotes: 0
Views: 1138
Reputation: 23087
Try this:
select (int) r.Field<byte>("FiscalYearId")
tinyint
is byte in c#, bytes can be casted to int
directly
EDIT:
According to this list: MSDN mapping CLR parameter list, tinyint is mapped to Byte. I think that line with where is also corrupted cause you are trying to convert smallint
to int32.
where r.Field<Int16>("FiscalYearNumber") == fYear
Int16
is equivalent to smallint
.
Upvotes: 4