Search code examples
c#asp.net-mvcentity-frameworkwcf-data-services

MVC with nested actions, WCF Data Service with EF5, and DataServiceQuery<>.Expand()


Consider this code:

var svc = new ProductDesignerEntities(AppSettings.ProductDesignerServiceLocation);

var scenariox = svc.Scenarios
    .Where(o => o.ID == id)
    .FirstOrDefault();

var scenario = svc.Scenarios
    .Expand(o => o.SomeNavigationProperty)
    .Where(o => o.ID == id)
    .FirstOrDefault();

When this code runs, scenario.SomeNavigationProperty will be unpopulated. Commenting out the code which populates scenariox fixes it. Why is this? Is it possible to fix this through configuration of the service context or the data service, or will I have to change the design of my code in some fashion?

The alternatives that I can think of are all inferior in some capacity:

  • Create a ProductDesignerEntities instance per action. This kills within-request caching almost entirely.
  • Create a ProductDesignerEntities instance per controller. Less annoying with a base controller class, but this kills caching between controllers, and wouldn't fix the issue if different actions in the same controller needed different sets of navigation properties from the same table.
  • Manually populate the property if it is empty. Difficult to consistently implement a manual solution like this; bound to be a source of bugs.
  • Always manually populate the property. Kind of defeats the purpose of navigation properties.
  • Ensure that all uses of the table within a request have the same .Expand() list. Extremely annoying and begging for hard-to-fix bugs.

I'm starting to lean toward the first alternative. It seems to have the least issues, despite the additional overhead of a new connection for each instance :/

EDIT: I managed to get the service queries to run through Fiddler, and they look correct. But the navigation property on scenario still winds up empty unless I comment out the scenariox code.


Solution

  • After doing further research, it appears that you're supposed to create a new ProductDesignerEntities instance within each use context anyway, so that's the solution I'll be going with. It bugs me a lot that I wasn't able to properly fix the problem, though!

    I'm going to write it off as either a very weird configuration issue, or a bug in WCF data services, because according to Fiddler, it does actually perform the request for the additional data; it just doesn't show up in the returned object.