开发者

IEnumerable.Single is throwing an exception

I have the following code which uses Entity Framework:

g_getWidgets = from getWidgets in g_libraryEntities.GET_Widgets() select getWidgets;
.
.
.
IQueryable<GET_Fragments_Result> iqueryable = g_getWidgets.AsQueryable<GET_Widgets_Result>();
var nameValueOb开发者_Python百科ject = from nv in iqueryable where nv.ID == int.Parse(key) select nv;
widget = nameValueObject.Single();

The widget = nameValueObject.Single(); line throws an exception saying "The result of a query cannot be enumerated more than once.

What is the proper way to perform this function? I just want to to return an item with the proper ID.


I would recommend using SingleOrDefault instead of FirstOrDefault.

Enumerable.FirstOrDefault()

Returns the first element of a sequence, or a default value if the sequence contains no elements.

Source: http://msdn.microsoft.com/en-us/library/bb340482.aspx

This means that if there are more than one match, only the first one found will be returned.

Enumerable.SingleOrDefault()

Returns the only element of a sequence, or a default value if the sequence is empty; this method throws an exception if there is more than one element in the sequence.

Source: http://msdn.microsoft.com/en-us/library/bb342451.aspx

This means that if there is more than one match an exception is thrown. This is useful if having duplicate entries is a data violation.


This will accomplish the same thing since you are only looking for a single match where the IDs are equal.

var nameValueObject = iqueryable.First( o => o.ID == int.Parse(key) );

If you don't want an exception to be thrown if a match is not found use FirstOrDefault instead. In that case the return value may be null, but if the item existing is an invariant I would prefer to use First and crash early.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜