How can I preempt the attempted assignment of DBNu

2019-09-11 08:26发布

问题:

The following code:

foreach (DataRow fillRateDataRow in dtFillRateResults.Rows)
{
    . . .
    var frbdbc = new FillRateByDistributorByCustomer
    {
        ShortName = fillRateDataRow["ShortName"].ToString(),
        Unit = fillRateDataRow["Unit"].ToString(),
        CustNumber = fillRateDataRow["Custno"].ToString(),
        MemberItemCode = fillRateDataRow["MemberItemCode"].ToString(),
        Qty = Convert.ToInt32(fillRateDataRow["Qty"]),
        QtyShipped = Convert.ToInt32(fillRateDataRow["QtyShipped"]),
        ShipVariance = fillRateDataRow["ShipVariance"].ToString(),
        CWeek = fillRateDataRow["CWeek"].ToString(),
        PAItemCode = fillRateDataRow["PAItemCode"].ToString(),
        PADescription = fillRateDataRow["PADescription"].ToString(),
        TransactionType = fillRateDataRow["TransactionType"].ToString(),
        SplitCase = fillRateDataRow["SplitCase"].ToString(),
        ReasonCode = fillRateDataRow["ReasonCode"].ToString(),
        ReasonDescription = fillRateDataRow["ReasonDescription"].ToString(),
        CompanyName = fillRateDataRow["CompanyName"].ToString()
    };

...fails once in a great while with, "Object cannot be cast from DBNull to other types. Exception Source: mscorlib Exception StackTrace: at System.DBNull.System.IConvertible.ToInt32(IFormatProvider provider) at System.Convert.ToInt32(Object value)"

So it seems that either Qty or QtyShipped are sometimes DBNull (the only int vals amidst a sea of strings).

Is there a way to say "if it's DBNull, assign 0 to the var" and thus avoid the exception?

回答1:

You can use a conditional expression:

QtyShipped = fillRateDataRow["QtyShipped"] != DBNull.Value ? Convert.ToInt32(fillRateDataRow["QtyShipped"]) : 0

If you need to do it a lot, making a helper method for this task would let you shrink your code for better readability.



回答2:

You can use this expression as well:

QtyShipped  = fillRateDataRow.Field<int?>("QtyShipped") ?? 0;