3

In our appliction we have a piece of code with some Linq-queries (EF) that sometimes throws an exception.

This has only happened to the end user, and we are not able to reproduce it so far.

From the logfile we got the following stacktrace for the exception:

System.InvalidOperationException: Sequence contains no elements at System.Linq.Enumerable.Single[TSource](IEnumerable1 source) at System.Data.Objects.ELinq.ObjectQueryProvider.<GetElementFunction>b__3[TResult](IEnumerable1 sequence) at System.Data.Objects.ELinq.ObjectQueryProvider.ExecuteSingle[TResult](IEnumerable1 query, Expression queryRoot) at System.Data.Objects.ELinq.ObjectQueryProvider.System.Linq.IQueryProvider.Execute[S](Expression expression) at System.Linq.Queryable.Count[TSource](IQueryable1 source) at MT3.uctXGrid.LoadLayout(String strUniqueID, Boolean rethrowException, List`1 visibleColumns)

In the method LoadLayout there are only 2 instances of Count(), and they are just operating on standard IQueryables which interrogate an entity type based on one integer field and select all fields (no aggregations or anything).

ex:

from p in cxt.genData where datId = ID

In the stacktrace, it seems like internally .Single() is being used which could throw an exception if there are no records.

But why is it using single if we are just calling .Count() ?

How can a query like

(from p in cxt.genData where datId = ID).Count()

throw a "sequence contains no elements" exception?

We have had other strange problems with queries as well, I'm starting to wonder if there are any issues with our version of EF maybe.

We are still on 4.0 at the moment. (Standard version which came with VS2010).

Has anyone got an idea what could be going on here?

Update: Here are the Linq-to-Entities queries we actually use

Dim qryLastLayout = From t In oContext.genGridLayouts Where t.layID = intCurrentLayoutID  
If Not IsNothing(qryLastLayout) AndAlso qryLastLayout.Count <> 0 Then

Dim qryPrintSettings = From p In oContext.genPrintSettings Where p.prtDefault = True  
If Not IsNothing(qryPrintSettings) AndAlso qryPrintSettings.Count <> 0 Then
4

2 に答える 2

0

.Any() メソッドを使用してみましたか?

if(cxt.genData.Any(x => x.datId == ID))
{
     // do something here
}
于 2012-12-17T12:39:32.653 に答える
0

Linq to Entities に関して注意すべきことの 1 つは、のセマンティクスがCount().NET のセマンティクスではなく、基礎となるデータソースのセマンティクスであるということです (言語統合の側面全体をいくらか弱体化させますが、まあ...)。これがあなたのような問題を引き起こすとは思いませんが、あなたにはわかりません。

詳細の MSDN リンク: http://msdn.microsoft.com/en-us/library/vstudio/bb738551.aspx#sectionSection5

于 2012-12-17T13:37:56.133 に答える