无法使用实体框架转换类型为nullable(对象)的对象

时间:2012-10-19 14:37:09

标签: entity-framework-4.1 asp.net-mvc-4 asp.net-web-api

我目前正在使用MVC 4 WebAPI w Entity Framework数据库首次建模的场景。在我的apicontroller中它给我一个错误:

  

发生了错误。   无法转换类型的对象   'WhereSelectEnumerableIterator 2[VB$AnonymousType_4 2 [System.Nullable 1[System.Guid],System.Collections.Generic.IEnumerable 1 [CK5.Airline],VB $ AnonymousType_5 1[System.Nullable 1的System.Guid]]]'   输入'System.Collections.Generic.IEnumerable 1[CK5.Airline]'. </ExceptionMessage> <ExceptionType>System.InvalidCastException</ExceptionType> <StackTrace> at lambda_method(Closure , Object , Object[] ) at System.Web.Http.Controllers.ReflectedHttpActionDescriptor.ActionExecutor.<>c__DisplayClass13.<GetExecutor>b__c(Object instance, Object[] methodParameters) at System.Web.Http.Controllers.ReflectedHttpActionDescriptor.ActionExecutor.Execute(Object instance, Object[] arguments) at System.Threading.Tasks.TaskHelpers.RunSynchronously[TResult](Func 1   func,CancellationToken cancellationToken)

    Public Class AirlineController
            Inherits ApiController

            ' GET api/Airline
            Function GetAirlines() As IEnumerable(Of Airline)
                Using db As New DefaultEntities
                    Return From p In db.Airlines.AsEnumerable Order By {p.Name} Group By ParentID = p.ParentID Into parentIDGroup = Group Select New With {.ParentID = ParentID}
                End Using
            End Function
End Class

在我的实体模型对象中,ParentID是一个可以为空的(guid)类型,我相信会导致问题。我在使用Linq2Sql scenerio之前已经有了这个工作,但是随着更新,这给了我一个问题。我不相信它是web api结构的问题,只是w实体框架。我哪里错了?

1 个答案:

答案 0 :(得分:1)

我修好了。 1)由于某些原因,EF不喜欢使用语句使用db作为新的DBContext,它在使用之前关闭连接我认为。 2)我不确定为什么,但它也不喜欢使用lambda语句。所以它不喜欢Order By或Group By声明。我必须考虑到这一点。 3)问题有点无关,但由于这是数据库的第一个EF,我还放入了globabl.asax这个语句:Database.SetInitializer(New DropCreateDatabaseIfModelChanges(Of DefaultEntities)())。认为它会根据变化更新模型或数据库。它欺骗了我。 = /