Gridview binded to LinqDataSource not showing association values

I’m working on a report screen for IssueTracker.NET and because this is going to be used purely for reporting on data this is a perfect match for leveraging the GridView & a LinqDataSource  to bind to, this will then give me dynamic filtering and paging out of the box splendid!

However after I had added the GridView & LinqDataSource wired the all up and ran the page there was a problem in that my association objects weren’t being displayed, hmm.. so I had code that looked like this:


    
        
    

Where User is a property on the current binded object my association object, so I went and re-checked the Linq to Sql generated code and sure enough the User property existed and was ok, so I re-ran with the debugger for the line above the Eval("User") returned null… then it struck me Lazy Loading perhaps the Eval method under the hood may not trigger a lazy loaded property to be retrieved (and in which case we don’t want lazy loading on this property anyway to cut down on DB trips).

So after some looking around it turns out you can control creating and assigning the DbContext object to the GridView via the ContextCreating event, so I subscribed to this and added the following:

protected void IssuesDataSource_ContextCreating(object sender, LinqDataSourceContextEventArgs e)
{
    var db = new IssueTrackerDbContextDataContext();
    db.ObjectTrackingEnabled = false;
    var loadOptions = new DataLoadOptions();
    loadOptions.LoadWith(x => x.User);
    db.LoadOptions = loadOptions;
    e.ObjectInstance = db;
}

Here is where you create your own custom DbContext object and set it how you want it, the important part for the above was the definition of the LoadOptions, don’t forget to assign it to the GridView via the e.ObjectInstance property.

Once I had this in place I did a re-run and I had my value displayed, so hopefully this will help people in the same boat.

Advertisements