LINQ to Entites:当检查项目的存在时,应该如何处理System.InvalidOperationException? [英] LINQ to Entites: How should I handle System.InvalidOperationException when checking for existance of an item?

查看:923
本文介绍了LINQ to Entites:当检查项目的存在时,应该如何处理System.InvalidOperationException?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一对一的关系,用户可以通过复选框进行编辑。 Foo的PK是ID,fid包含复选框中的id。

I have a many-to-one relationship that users can edit via checkboxes. PK of Foo is ID, and fid contains the id from the checkbox.

我正在检查一下元素是否存在:

I'm checking to see if an element exists with:

Foo ent;
try
{
  ent = ctx.Foo.First(f => f.ID == fid);
}
catch (System.InvalidOperationException ioe)
{
  ent = new Foo();
}

在我看来,我应该能够做到这一点,而不会抛出异常。

It seems to me that I should be able to do this without throwing an exception. What would be the best way to do this?

推荐答案

InvalidOperationException 你有消息:

Sequence contains no matching element

First 的行为是如果没有找到元素,它会抛出此异常。

The behaviour of First is that it throws this exception if the element is not found.

您可以使用 FirstOrDefault 而不是首先并检查。可以使用null-coalescing运算符( ?? )来进行此检查。

You can use FirstOrDefault instead of First and check for null. The null-coalescing operator (??) can be used to make this check.

Foo ent = ctx.Foo.FirstOrDefault(f => f.ID == fid) ?? new Foo();

还要注意,有一对类似的功能, Single SingleOrDefault ,如果找到多个匹配的元素,则抛出异常。在您的具体情况下,假设身份应该是唯一的,使用 SingleOrDefault 可能更合适。

Note also that there is a similar pair of functions, Single and SingleOrDefault that throw an exception if more than one matching element is found. In your specific case, assuming that the identities should be unique, it might be more appropriate to use SingleOrDefault.

这篇关于LINQ to Entites:当检查项目的存在时,应该如何处理System.InvalidOperationException?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆