LINQ to Entites: How should I handle System.InvalidOperationException when checking for existance of an item?

笑着哭i 提交于 2019-12-11 06:32:47

问题


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?


回答1:


The InvalidOperationException you get has the message:

Sequence contains no matching element

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

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();

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.



来源:https://stackoverflow.com/questions/2640303/linq-to-entites-how-should-i-handle-system-invalidoperationexception-when-check

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!