C# 如果变量不为null,则转换为相关类型
我在将CRM查询的结果映射到自定义模型时遇到问题。如果该值为null,我将尝试使用以下代码:C# 如果变量不为null,则转换为相关类型,c#,nullable,C#,Nullable,我在将CRM查询的结果映射到自定义模型时遇到问题。如果该值为null,我将尝试使用以下代码: foreach (account acc in accounts.BusinessEntities) { if ((acc.accountid != null)) { try { Account newAccount = new Account(); newAccount.AccountID = acc.ac
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为空时,它将不允许我将日期的值设置为可空日期,并且它似乎在继续尝试转换空值,因为我收到一个对象引用错误您可以更改:
newAccount.DepositDate = acc.new_depositdate.Equals(DBNull.Value) ? (DateTime?)null : Convert.ToDateTime(acc.new_depositdate.ToString());
到
这样,您就不会试图针对空值调用.Equals()
(这可能是导致NullReferenceException
的原因)
您可能还必须将更改应用于其他分配,以防止出现进一步的异常。您是指
null
还是DBNull
?如果它真的是null
,那么显然,调用.Equals
将抛出null引用异常。请发布准确的错误消息+堆栈跟踪?
newAccount.DepositDate = acc.new_depositdate == null ? (DateTime?)null : Convert.ToDateTime(acc.new_depositdate.ToString());