Reputation: 1327
In my ASP.NET MVC WebApi project I have a Repository (with an Interface) that queries the DB via a simple Linq SingleOrDefault command and then outputs everything to The Controller. (EF = Database first against Oracle DB)
The Problem is that, when I turn on Lazy Loading (via the EDMX file property) the get is loading forever and there is no response. If I turn off Lazy Loading everything works fine?
Even stranger ist that when I put all the query in a console app and output everything via Console.WriteLine it works also with lazy loading?
Interface:
Public Interface IMedienRepository
Function [Get](id As Integer) As MEDIEN
End Interface
Repository
Private db As EFEntities
Public Sub New()
db = New EFEntities
End Sub
Public Function [Get](id As Integer) As MEDIEN Implements IMedienRepository.[Get]
Dim _medien = db.MEDIEN.SingleOrDefault(Function(m) m.MEDIENNR = id)
If _medien Is Nothing Then
Throw New NotFoundException()
End If
Return _medien.SingleOrDefault()
End Function
Controller
Private _repository As IMedienRepository
Public Sub New()
Me.New(New MedienRepository())
End Sub
Public Sub New(repository As IMedienRepository)
_repository = repository
End Sub
Public Function GetValue(id As Integer) As MEDIEN
Try
Return _repository.Get(id)
Catch generatedExceptionName As NotFoundException
Throw New HttpResponseException(New HttpResponseMessage() With { _
.StatusCode = System.Net.HttpStatusCode.NotFound _
})
End Try
End Function
FYI: It isn't working even when I put the query directly into the controller!
I would be grateful if anybody knows about this issue and could help me because I like to use the Lazy loading feature in my MVC Views.
My work around for the Moment is to turn Lazy Loading off (db.ContextOptions.LazyLoadingEnabled = False
) for calls via the WebApi ...
Upvotes: 2
Views: 2456
Reputation: 34810
Given the behavior you describe, I suspect the lazy loading is causing (for some reason) the loading of a LOT of data from the database, which takes a long time and looks like no response. Turning lazy loading off ensures that only the first "level" of your query is returned, without populating any collection properties.
If these calls are for a WebAPI, I'm not sure you would get any real benefit from lazy loading. API calls should be very deterministic in the way they query the database and return strictly defined result sets. Writing a well-performing API is hard (just ask the StackOverlow team!) and query performance is critical.
Upvotes: 1