ToList(),Any(),Count(),Sum()上的Linq错误

时间:2019-03-06 10:30:58

标签: c# entity-framework linq

我遇到以下错误,它们都与system.linq有关。奇怪的是,该方法有时似乎可以正常工作,错误并没有始终如一地发生。

Count()代码:

using (var dbContext = new Entities(GlobalStuff.EntityConnection))
{
    heartBeat.NumSlipsInSecurityUploadQueue = dbContext.SecurityUploadQueues.Count();
    heartBeat.NumSlipsInDataStreamQueue = dbContext.DataStreamQueues.Count();
}

SecurityUploadQueues属性:

Public ReadOnly Property SecurityUploadQueues() As ObjectSet(Of SecurityUploadQueue)
        Get
            If (_SecurityUploadQueues Is Nothing) Then
                _SecurityUploadQueues = MyBase.CreateObjectSet(Of SecurityUploadQueue)("SecurityUploadQueues")
            End If
            Return _SecurityUploadQueues
        End Get
    End Property

    Private _SecurityUploadQueues As ObjectSet(Of SecurityUploadQueue)

SecurityUploadQueue属性是一个EntityObject

Count()错误:

  

上传HeartBeat System.InvalidOperationException时出错:序列包含多个元素
     在System.Linq.Enumerable.Single [TSource](IEnumerable 1 source) at System.Data.Objects.ELinq.ObjectQueryProvider.<>c__11 1.b__11_3(IEnumerable 1 sequence) at System.Data.Objects.ELinq.ObjectQueryProvider.ExecuteSingle[TResult](IEnumerable 1条查询,表达式queryRoot)中
     在System.Data.Objects.ELinq.ObjectQueryProvider.System.Linq.IQueryProvider.Execute [S](表达式)
     在System.Linq.Queryable.Count [TSource](IQueryable`1源)
     在SettlerService.SettlerService.UploadHeartBeat()

Any()代码:

var dataToUpload = (from bet in dbContext.DataStreamQueues select bet).Take(200);
if (dataToUpload.Any())

Any()错误:

  

System.InvalidOperationException:从   物化到'System.Boolean'类型的'System.Int32'类型不是   有效。在   System.Data.Common.Internal.Materialization.Shaper.ErrorHandlingValueReader 1.GetValue(DbDataReader reader, Int32 ordinal) at lambda_method(Closure , Shaper ) at System.Data.Common.Internal.Materialization.Coordinator 1.ReadNextElement(Shaper   成型机)   System.Data.Common.Internal.Materialization.Shaper 1.SimpleEnumerator.MoveNext() at System.Linq.Enumerable.Single[TSource](IEnumerable 1源)位于   System.Data.Objects.ELinq.ObjectQueryProvider。<> c__11 1.<GetElementFunction>b__11_3(IEnumerable 1   顺序)   System.Data.Objects.ELinq.ObjectQueryProvider.ExecuteSingle [TResult](IEnumerable 1 query, Expression queryRoot) at System.Data.Objects.ELinq.ObjectQueryProvider.System.Linq.IQueryProvider.Execute[S](Expression expression) at System.Linq.Queryable.Any[TSource](IQueryable 1源)
  在SettlerService.SettlerService.UploadDataStream()

我做了一些谷歌搜索,在这个问题上找不到很多东西。我认为这可能与system.core库的版本有关(system.linq是该库的一部分),但是看不到问题。我正在使用.Net 4.7.2

1 个答案:

答案 0 :(得分:0)

第二错误表明您的DataStreamQueues数据库表中有一列类型为Int32的列,但DataStreamQueues实体中的等效属性的类型是布尔因此请检查所有列和属性类型是否匹配。
关于 first 例外,这有点奇怪!因为此异常表明您在代码中的某个位置上正在对具有多个项目的集合调用Single()方法,并且Single()仅期望一个项目,所以它引发了异常,但是我看不到对{ {1}}在提供的代码中。