Search code examples
c#asp.net-mvc-3entity-frameworkwcf-data-services

WCF Data Services Collection Loading


Given the following example model (which reflect my Entity Framework entities, properties omitted for brevity):

public class Company
{
    public string Name { get; set; }
    public IList<Department> Departments { get; set; }
}

public class Department
{
    public string Name { get; set; }
    public IList<Employee> Employees { get; set; }
}

public class Employee
{
    public string Name { get; set; }
}

I am consuming a WCF Data Service from my Web UI to get at these entities. What I'm basically after is a best pratice / more elegant way of loading each Company which will have each respetive Department which will have each respective Employee eagerly loaded.

At the moment my code looks something like this:

var proxy = new MyWCFDataService(url);

var companies = proxy.Companies;

foreach (var company in companies)
{
    proxy.LoadProperty(company, "Departments");

    foreach (var dept in company.Departments)
    {
        proxy.LoadProperty(dept, "Employees");
    }
}

If I must do the above, then I'd like to do this in a Service Operation so I can get this spaghetti mess out of my UI controllers. I've tried to do this with the following:

[WebGet]
public IQueryable<Company> GetCompanies()
{
    var companies = this.CurrentDataSource.Companies.Include("Departments");

    return companies;
}

I'm getting my Company collection back fine, but again I have no Department collection it's just an empty list.

Any ideas anyone?


Solution

  • var companies = proxy.Companies.Expand("Departments");