使用存储过程,Linq 数据不能为空



我尝试将存储过程与linq一起使用。

如果result.FirstOrDefault().CustomerName为空,则出现以下异常,

NullReferenceException was unhandled
对象引用未设置为对象的实例

使用以下代码:

var result = context.sp_CustomerInformation(CustomerId).ToList();
var MyCustomerName = result.FirstOrDefault().CustomerName;

我哪里做错了?

遇到了该错误,因为当结果不匹配时FirstOrDefault()将返回该类型的默认值。在这种情况下,默认值为 null。因此,您正在尝试访问空对象的属性,这将导致NullReferenceException

您需要执行以下操作:

var result = context.sp_CustomerInformation(CustomerId).ToList();
var object = result.FirstOrDefault();
var MyCustomerName = "";
if(object != null)
    MyCustomerName = object.CustomerName;
else
    // do something here if there were no results

对于它的价值,您可能还可以组合您的result查询:

var result = context.sp_CustomerInformation(CustomerId).FirstOrDefault();

而不是ToList(),这将返回所有匹配的记录。 FirstOrDefault只会获得第一条记录。然后,您将能够使用result而不是上面示例中的object

最新更新