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

时间:2013-09-27 13:36:13

标签: c# sql linq stored-procedures entity

我尝试使用linq存储过程。

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

  

NullReferenceException未处理   对象引用未设置为对象的实例

使用以下代码:

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

我哪里出错了?

1 个答案:

答案 0 :(得分:1)

您遇到了该错误,因为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