2016-07-13 7 views
0

でない場合、値は、私は次のコードを使用しようとしていますnullの場合、私は私のカスタムモデルにCRMクエリの結果をマッピングに支障が生じています:は、関連するタイプに変換変数がnull

foreach (account acc in accounts.BusinessEntities) 
{ 
    if ((acc.accountid != null)) 
    { 
     try 
     { 
      Account newAccount = new Account(); 
      newAccount.AccountID = acc.accountid.Value; 
      newAccount.MPRN = Convert.ToInt64(acc.new_mprnnumber); 
      newAccount.CustomerNumber = acc.new_customernumber; 
      newAccount.CurrentLiftDate = acc.new_preferredliftday.Value.Equals(DBNull.Value) ? 0 : Convert.ToInt32(acc.new_preferredliftday.Value); 
      newAccount.MonthlyAmount = acc.new_regularliftamount.Value.Equals(DBNull.Value) ? 0 : Convert.ToDecimal(acc.new_regularliftamount.Value); 
      newAccount.DepositDate = acc.new_depositdate.Equals(DBNull.Value) ? (DateTime?)null : Convert.ToDateTime(acc.new_depositdate.ToString()); 
      newAccount.DepositAmount = acc.new_depositamount.Value.Equals(DBNull.Value) ? 0 : Convert.ToDecimal(acc.new_depositamount.Value); 
      db.Accounts.Add(newAccount); 
      db.SaveChanges(); 
     } 
     catch(Exception ex) 
     { 
      System.Diagnostics.EventLog.WriteEntry("Application", "ERROR CREATING ACCOUNT IN BILLING ENGINE : " + ex.Message, System.Diagnostics.EventLogEntryType.Error); 
     } 
    } 
} 

acc.new_depositdateがnullの場合、日付の値をnull可能な日付に設定することはできません。オブジェクト参照エラーが発生したため、NULL値を変換しようとし続けているようです。

+0

「ヌル」または「DBNull」を意味しますか?それが本当に 'null'の場合、明らかに' .Equals'の呼び出しはnull参照例外をスローします。正確なエラーメッセージ+スタックトレースを投稿してください。 – sstan

答えて

1

newAccount.DepositDate = acc.new_depositdate.Equals(DBNull.Value) ? (DateTime?)null : Convert.ToDateTime(acc.new_depositdate.ToString()); 

あなたは(おそらくあなたのNullReferenceExceptionの原因である)、null値に対して.Equals()を呼び出そうとしていないこの方法で

newAccount.DepositDate = acc.new_depositdate == null ? (DateTime?)null : Convert.ToDateTime(acc.new_depositdate.ToString()); 

へ。

さらなる例外を防ぐために、変更を他の割り当てに適用する必要がある場合もあります。

関連する問題