Wednesday, April 13, 2011

Can't access entity from within the View

I'm passing IList<Post> to View(posts).
Post is a linqToSql generated model class.
Post has an FK relation to the Category table by Id.

When I'm iterating over IList<Post> inside my View and trying to access post.Category.Title I'm receiving an error:

System.ObjectDisposedException: Cannot access a disposed object. Object name: 'DataContext accessed after Dispose.'.

How can I get Category.Title for each of my Posts right from View?

From stackoverflow
  • Yes, actually what the error tells you! In other words, keep your DataContext open till you finished working with the data.

    Previously I just create a DataContext per page request, and dispose it at the end of the request. Worked relatively well.

    Dmytro Leonenko : Thanks a lot for pointing me! I've just forgot that I'm writing: using (BlaBlaDataContext dataContext = new BlaBlaDataContext()) { return bla-bla-bla; } :)

0 comments:

Post a Comment