IEnumerable.Single 引发异常
我有以下使用实体框架的代码:
g_getWidgets = from getWidgets in g_libraryEntities.GET_Widgets() select getWidgets;
.
.
.
IQueryable<GET_Fragments_Result> iqueryable = g_getWidgets.AsQueryable<GET_Widgets_Result>();
var nameValueObject = from nv in iqueryable where nv.ID == int.Parse(key) select nv;
widget = nameValueObject.Single();
widget = nameValueObject.Single();
行抛出异常,指出“查询的结果不能枚举多次。
执行此功能的正确方法是什么?我只想返回具有正确 ID 的项目。
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 nameValueObject = 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.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
我建议使用
SingleOrDefault
而不是FirstOrDefault
。这意味着如果有多个匹配项,则仅返回找到的第一个。
这意味着如果有多个匹配项,则会引发异常。如果重复条目构成数据违规,这非常有用。
I would recommend using
SingleOrDefault
instead ofFirstOrDefault
.This means that if there are more than one match, only the first one found will be returned.
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.
这将完成同样的事情,因为您只寻找
ID
相等的单个匹配项。如果您不希望在未找到匹配项时引发异常,请改用
FirstOrDefault
。在这种情况下,返回值可能为 null,但如果现有项目是不变量,我更愿意使用First
并尽早崩溃。This will accomplish the same thing since you are only looking for a single match where the
ID
s are equal.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 useFirst
and crash early.