如何检查ObjectResult集合是否为空?

时间:2012-06-24 13:15:44

标签: c# collections ienumerable nullable executestorequery

我有这段代码检查数据库中的最后一个customer_id。

ObjectResult<int?> last_customer_id_collection = MainForm.eggsContext.ExecuteStoreQuery<int?>("select MAX(customer_id) from customers");

然后我得到下一个所需的ID

new_customer_id = last_customer_id_collection.FirstOrDefault<int?>().Value + 1;

它正在工作,但是当处理新的空数据库时,语句last_customer_id_collection.FirstOrDefault<int?>()会抛出InvalidOperationException。

如何在不尝试catch的情况下检查last_customer_id_collection是否为空?

(p.s。我试图检查last_customer_id_collection.Any<int?>()last_customer_id_collection.Count<int?>()或DefaultIfEmpty等,但我尝试的所有内容都会导致此异常)

1 个答案:

答案 0 :(得分:1)

您收到InvalidOperationException,因为Nullable<T>.HasValue将返回false。

如果查询返回值为null,则需要修改代码以不调用.Value

var custId = last_customer_id_collection.FirstOrDefault<int?>();
if(custId.HasValue)
    DoStuffWithId();
else
    DoStuffWithNullResult();

小例子,展示了Nullables的潜在混淆行为 这将打印:

“Null!”,“No Value but no NullReferenceException”,然后是“Oops,InvalidOperationException”

List<int?> values = new List<int?>();

var test = values.FirstOrDefault();

if (test == null)
    Console.WriteLine("Null!");

if (test.HasValue)
    Console.WriteLine(test.Value);
else
    Console.WriteLine("No Value but no NullReferenceException");

try
{
    int value = test.Value;
}
catch(InvalidOperationException)
{
    Console.WriteLine("Oops, InvalidOperationException");
}