Sql – Can’t access entity from within the View

asp.net-mvclinq-to-sql

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?

Best Answer

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.

Related Topic