在不应该时引发异常


private async Task<long> InsertCustomerRecord(CreateCustomerModel model)
{
Int64 phoneNumber = 0;
var isParsed = Int64.TryParse(model.PhoneNumber, out phoneNumber);
if (!isParsed)
phoneNumber = 0;
var USPSAddressValidatedId = (int)model.USPSAddressValidated;
try
{
IDataParameter[] parameters = new IDataParameter[]
{
new SqlParameter("@FirstName", model.FirstName.ToUpper()),
new SqlParameter("@LastName", model.LastName.ToUpper()),
//new SqlParameter("@MiddleInitial", model.MiddleInitial),
new SqlParameter("@AddressLine1",model.AddressLine1.ToUpper() ?? ""),
new SqlParameter("@AddressLine2",model.AddressLine2.ToUpper() ?? ""),
new SqlParameter("@City",model.City.ToUpper()),
new SqlParameter("@State",model.State.ToUpper()),
new SqlParameter("@CountyCode",model.CountyCode.ToUpper()),
new SqlParameter("@ZipCode",model.ZipCode),
new SqlParameter("@DateOfBirth",model.DateOfBirth.ToShortDateString()),
new SqlParameter("@Phone",phoneNumber),
new SqlParameter("@Email",model.EmailAddress.ToUpper()??""),
new SqlParameter("@PersonalRepresentative",model.CustomerClass.ToUpper()),
new SqlParameter("@ExpiryDate", model.ExpirationDate),
new SqlParameter("@CustomerClass", model.Customer_Class),
new SqlParameter("@USPSAddressValidated",USPSAddressValidatedId ),
new SqlParameter("@ImportFromLegacySystem", model.ImportFromLegacySystem)
};

return await InsertUpdateProcedure("RF_InsertCustomerCard", parameters);
}
catch (Exception e)
{
Console.WriteLine(e.Message);
return 0;
}
}

抛出的异常是

{"Object reference not set to an instance of an object."}
Data: {System.Collections.ListDictionaryInternal}

如果您怀疑某个东西可能为空:

model.EmailAddress
^^^^^^^^^^^^
this might be null

您需要在其上使用null传播运算符:

model.EmailAddress?.ToUpper() ?? ""
^^

这意味着,如果是null,则在.EmailAddress返回null时,运算链的求值将停止,并且子表达式(model.EmailAddress?.ToUpper()(将解析为null。然后,它将被零合并运算符??拾取,并转换为您放在运算符右侧的任何内容。如果它是一个常数,比如"",那么整个表达式就保证不是空

您可以在属性和方法返回值上多次使用这些运算符:

thing.Prop?.Method() ?? thing.OtherProp?.OtherMethod()?.AnotherProp ?? "Constant"

如果集合可能为null,那么还有一个允许null的索引器:

//in case the collection is null, or the thing at index 0 is null, or its Property is null...
thing.Collection?[0]?.Property?.Something() ...
^^

最新更新