News


Having just help another developer with this issue, I thought I’d write a quick post about the cause of the ObjectDisposedException exception when working with Entity Framework.

It is important to be aware of two things when working with Entity Framework

1) The data context must not be disposed of until all the data is fetched from the database.

2) A linq statement creates an IQueryable, which is not executed until you enumerate over it (e.g. use it in a for each loop) or convert it to a list or an array.

Lets see and example:

Public Function GetProducts() As IEnumerable(Of Product)
    Using entities As New AdventureWorksEntities
        Return From p in entities.Products Where Not p.IsDiscontinued
    End Using
End Function

Now, If we call the above function like this:

For Each product In GetProducts()
    Console.WriteLine(product.Name)
Next

We will get an ObjectDisposedException exception because the query is not executed until we get to the For Each loop, whereas the data context is disposed of before leaving the GetProducts() function.

To avoid this problem simply call .ToList() on the query inside the Using block so it is executed there and then:

Public Function GetProducts() As IEnumerable(Of Product)
    Using entities As New AdventureWorksEntities
        Return (From p in entities.Products
                Where Not p.IsDiscontinued).ToList()
    End Using
End Function


Comments

No comments posted yet.
Post A Comment
Title:
Name:
Email:
Comment:
Verification: