如何找到InvalidCastException错误?

时间:2011-12-01 16:28:17

标签: c# model .net

我使用IBM i数据处理 ton ,我不能使用EF来处理这些数据。所以我做了类似以下的事情:

DataTable dt = new DataTable();
using (iDB2Connection conn = new iDB2Connection(_connString))
{
    using (iDB2Command cmd = new iDB2Command(sb.ToString(), conn))
    {
        conn.Open();
        using (iDB2DataAdapter da = new iDB2DataAdapter(cmd)) { da.Fill(dt); }
        conn.Close();
    }
}

从那里我可以通过以下方式对数据建模:

var billHistory = from i in dt.AsEnumerable()
    select new BillHistory
    {
        CustomerId = i.Field<int>("CCUSTN"),
        DueDate = Convert.ToDateTime(i.Field<decimal>("CDUEDT").ToString("0000-00-00")),
        Type = i.Field<string>("CTYPE"),
        RunDate = Convert.ToDateTime(i.Field<decimal>("CDTRUN").ToString("0000-00-00")),
        MeterReadDate = Convert.ToDateTime(i.Field<decimal>("CDREAD").ToString("0000-00-00")),
        PreviousReadDate = Convert.ToDateTime(i.Field<decimal>("CPREVD").ToString("0000-00-00")),
        DaysBetweenReads = i.Field<int>("CDAYS"),
        BillSendDate = Convert.ToDateTime(i.Field<decimal>("CDSENT").ToString("0000-00-00")),
        Meter1Reading = i.Field<int>("CMETR1"),
        Meter2Reading = (i.Field<int>("CMETR2") == 0) ? null : i.Field<int?>("CMETR2"),
        ConsumptionInUnits = i.Field<int>("CCONSU"),
        PreviousReading = i.Field<int>("CPREV1"),
        AverageUnitsOver3Months = i.Field<int>("CAVG3M"),
        LastMonthUnits = i.Field<int>("CUNT1M"),
        PercentChange = i.Field<int>("CPCTCH"),
        IsEstimated = (i.Field<string>("CESTIM") == "Y") ? true : false,
        IsFinalBill = (i.Field<string>("CFINAL") == "Y") ? true : false,
        SprinklerLocation = (i.Field<int>("CSPRLO") == 0) ? null : i.Field<int?>("CSPRLO"),
        SprinklerReading = (i.Field<int>("CSPRMETR") == 0) ? null : i.Field<int?>("CSPRMETR"),
        SprinklerConsumptionInUnits = (i.Field<int>("CSPRCONSU") == 0) ? null : i.Field<int?>("CSPRCONSU"),
        SprinklerPreviousReading = (i.Field<int>("CSPRPREV1") == 0) ? null : i.Field<int?>("CSPRPREV1"),
        SprinklerAverageUnitsOver3Months = (i.Field<int>("CSPRAVG3M") == 0) ? null : i.Field<int?>("CSPRAVG3M"),
        SprinklerLastMonthUnits = (i.Field<int>("CSPRUNT1M") == 0) ? null : i.Field<int?>("CSPRUNT1M"),
        SprinklerPercentChange = (i.Field<int>("CSPRPCT") == 0) ? null : i.Field<int?>("CSPRPCT"),
        PreviousBalance = (i.Field<decimal>("CPREVS") == 0) ? null : i.Field<decimal?>("CPREVS"),
        PaymentAdjustment = (i.Field<decimal>("CPAYAD") == 0) ? null : i.Field<decimal?>("CPAYAD"),
        WaterCost = (i.Field<decimal>("CWATER") == 0) ? null : i.Field<decimal?>("CWATER"),
        SewerCost = (i.Field<decimal>("CSEWER") == 0) ? null : i.Field<decimal?>("CSEWER"),
        RefuseCost = (i.Field<decimal>("CREFUS") == 0) ? null : i.Field<decimal?>("CREFUS"),
        LawnSprinklerCost = (i.Field<decimal>("CLAWNS") == 0) ? null : i.Field<decimal?>("CLAWNS"),
        ACCost = (i.Field<decimal>("CAIR") == 0) ? null : i.Field<decimal?>("CAIR"),
        FireLineCost = (i.Field<decimal>("CFIREL") == 0) ? null : i.Field<decimal?>("CFIREL"),
        HydrantCost = (i.Field<decimal>("CHYDRA") == 0) ? null : i.Field<decimal?>("CHYDRA"),
        StormWaterCost = (i.Field<decimal>("CSTORM") == 0) ? null : i.Field<decimal?>("CSTORM"),
        SpecialBillTaxable = (i.Field<decimal>("CSPECT") == 0) ? null : i.Field<decimal?>("CSPECT"),
        SpecialBillNonTaxable = (i.Field<decimal>("CSPECN") == 0) ? null : i.Field<decimal?>("CSPECN"),
        StateTax = (i.Field<decimal>("CSTTAX") == 0) ? null : i.Field<decimal?>("CSTTAX"),
        RefuseTax = (i.Field<decimal>("CRFTAX") == 0) ? null : i.Field<decimal?>("CRFTAX"),
        StateConnectionFee = (i.Field<decimal>("CSCFEE") == 0) ? null : i.Field<decimal?>("CSCFEE"),
        CityTax = (i.Field<decimal>("CCITAX") == 0) ? null : i.Field<decimal?>("CCITAX"),
        ACHCredit = (i.Field<decimal>("CACHCR") == 0) ? null : i.Field<decimal?>("CACHCR"),
        PaperlessCredit = (i.Field<decimal>("CPPLCR") == 0) ? null : i.Field<decimal?>("CPPLCR"),
        OneTimeDescription = (i.Field<string>("C1XDES") == String.Empty) ? null : i.Field<string>("C1XDES"),
        OneTimeCredit = (i.Field<decimal>("C1XAMT") == 0) ? null : i.Field<decimal?>("C1XAMT"),
        LateFee = (i.Field<decimal>("CLATFE") == 0) ? null : i.Field<decimal?>("CLATFE"),
        NSFFee = (i.Field<decimal>("CNSFFE") == 0) ? null : i.Field<decimal?>("CNSFFE"),
        TotalBill = (i.Field<decimal>("TOTAL_BILL") == 0) ? null : i.Field<decimal?>("TOTAL_BILL")
    };

这是精确的复制粘贴(抱歉长度)。真正的问题出现在我有一个InvalidCastException时,我该如何找到问题?我过去已经慢慢想出来了,但我希望有更好的方法。

以下是例外情况:

System.InvalidCastException was unhandled
  Message=Specified cast is not valid.
  Source=System.Data.DataSetExtensions
  StackTrace:
       at System.Data.DataRowExtensions.UnboxT`1.ValueField(Object value)
       at System.Data.DataRowExtensions.Field[T](DataRow row, String columnName)
       at SendToInternet.Model.IbmIDatabase.<GetCustomerHistory>b__11(DataRow i) in C:\Documents and Settings\ispa2\My Documents\Visual Studio 2010\Projects\SendToInternet\SendToInternet\Model\IbmIDatabase.cs:line 514
       at System.Linq.Enumerable.WhereSelectEnumerableIterator`2.MoveNext()
       at SendToInternet.Controllers.UtilityBillController.ProcessAllUtilityBills() in C:\Documents and Settings\ispa2\My Documents\Visual Studio 2010\Projects\SendToInternet\SendToInternet\Controllers\UtilityBillController.cs:line 131
       at SendToInternet.Program.Main(String[] args) in C:\Documents and Settings\ispa2\My Documents\Visual Studio 2010\Projects\SendToInternet\SendToInternet\Program.cs:line 59
       at System.AppDomain._nExecuteAssembly(RuntimeAssembly assembly, String[] args)
       at System.AppDomain.ExecuteAssembly(String assemblyFile, Evidence assemblySecurity, String[] args)
       at Microsoft.VisualStudio.HostingProcess.HostProc.RunUsersAssembly()
       at System.Threading.ThreadHelper.ThreadStart_Context(Object state)
       at System.Threading.ExecutionContext.Run(ExecutionContext executionContext, ContextCallback callback, Object state, Boolean ignoreSyncCtx)
       at System.Threading.ExecutionContext.Run(ExecutionContext executionContext, ContextCallback callback, Object state)
       at System.Threading.ThreadHelper.ThreadStart()
  InnerException: 

第514行是var billHistory = from i in dt.AsEnumerable(),这是没用的。除非b__11是,但我仍然没有看到任何问题。

2 个答案:

答案 0 :(得分:3)

如果您查看InvalidCastException的文字,其中会包含一个行号。它提到的行号是InvalidCastException的来源。

答案 1 :(得分:1)

你在哪个变量中得到InvalidCastException

考虑您是否在以下字段中获得InvalidCastException。然后尝试这种方式

try
{
    CustomerId = i.Field<int>("CCUSTN");
}
catch(InvalidCastException)
{
    CustomerId = "yourValue";
}