I’m trying to query my EF Model (using ASP.NET MVC WebApi) but only the first version (using SingleOrDefault) works and not the second one and i can’t get my head around it!
Working:
Public Overloads Shared Function GetById(id As Integer) As MEDIA
Dim db As New EFEntities()
Dim r As New MEDIA()
r = db.MEDIA.SingleOrDefault(Function(p) p.id = id)
Return r
End Function
Not Working:
Error : Unable to cast object of type ‘System.Data.Objects.ObjectQuery`1[Data.MEDIA]’ to type ‘Data.MEDIA’
Public Overloads Shared Function GetById(id As Integer) As MEDIA
Dim db As New EFEntities()
r = From media In db.MEDIA
Where media.id= id _
Select media
Return r
End Function
I would really appreciate it if somebody could show me how to get the second version running and explain what the problem is!
In your first example, the line:
initializes a single MEDIA object.
In your second example, however, the line:
initializes a collection of MEDIA objects – incompatible types.
If you changed your return expression in your second example to:
and stick
Dimin front of the initialization ofrit’ll work.