说明:本站是 http://access911.net 的附属社区之一
C# LINQ 提示 sequence contains no elements
作者:陈格 日期:2010-02-22
C# LINQ 提示 "sequence contains no elements"错误
System.InvalidOperationException: Sequence contains no elements
While using LINQ, let’s say you decide to do something similar to the following…
NorthWindDataContext dc = new NorthWindDataContext();
Product p = dc.Products.First(p1 => p1.ProductName.StartsWith("My New Product"));
if (p == null)
return;
dc.Products.DeleteOnSubmit(p);
dc.SubmitChanges();
ShowProducts();
Everything would be fine if you do have a product whose name starts with “My New Product”, but what do you think would happen if that’s not the case? Well surprisingly... you would get an un-handled runtime exception!!!
Exception Details: System.InvalidOperationException: Sequence contains no elements
Source Error:
Line 69: NorthWindDataContext dc = new NorthWindDataContext();
Line 70:
Line 71: Product p = dc.Products.First(p1 => p1.ProductName.StartsWith("My New Product"));
Line 72: if (p == null)
Line 73: return;
To get rid of this error, instead of using dc.Products.First, use dc.Products.FirstOrDefault and you should be good!
Happy Coding.
Rahul
别以为后面用 p==null 可以判断出是否包含,应该用 FirstOrDefault 作为方法来获取
System.InvalidOperationException: Sequence contains no elements
While using LINQ, let’s say you decide to do something similar to the following…
NorthWindDataContext dc = new NorthWindDataContext();
Product p = dc.Products.First(p1 => p1.ProductName.StartsWith("My New Product"));
if (p == null)
return;
dc.Products.DeleteOnSubmit(p);
dc.SubmitChanges();
ShowProducts();
Everything would be fine if you do have a product whose name starts with “My New Product”, but what do you think would happen if that’s not the case? Well surprisingly... you would get an un-handled runtime exception!!!
Exception Details: System.InvalidOperationException: Sequence contains no elements
Source Error:
Line 69: NorthWindDataContext dc = new NorthWindDataContext();
Line 70:
Line 71: Product p = dc.Products.First(p1 => p1.ProductName.StartsWith("My New Product"));
Line 72: if (p == null)
Line 73: return;
To get rid of this error, instead of using dc.Products.First, use dc.Products.FirstOrDefault and you should be good!
Happy Coding.
Rahul
别以为后面用 p==null 可以判断出是否包含,应该用 FirstOrDefault 作为方法来获取
评论: 0 | 引用: 0 | 查看次数: 314
发表评论
用手机拍码上网吧, QuickMark可以识别 |
拍码写信吧 |
本站描述 |
上一篇
下一篇

文章来自:
Tags:





