web 2.0

Enable associated entities to load with base entity

Associated entitites I encoutered a problem, when I wanted to load Employees entities also with some associated entities at once, from the well-known AdwentureWorks database model (in Entity Framework) via DomainService/Context in a .NET RIA Services SL Application.

So if you encountered the same problem, that initially your associated/referenced entities are null when loaded, read more to see how to solve this issue.

A week ago, I wanted to bind the DataGrid with Employees from AdventureWorks DB with contact information as FistName, LastName, etc. Contact is with Employee table associated by ContactID foreign key, so in SQL I would go for inner join (or left outer join) on these two tables.

In my Data Model I had the Employee entity with navigation property Contact.

But when you load it by a service query in your domain context on the client, you’ll basicly populate your domain context Employees collection with data. Navigation property to Manager is working since, this is also an already laoded Employee entity. But all the other navigation properties like Contact are null. Of course, this is logical, since you probably want don’t want to transfer a large amount of data, you know, all the associated entities, which you usually do not need.

The usual scenario is that you have a list of entities and you download some detail only after one is selected, for example. In my problem, I had to either change the domain model in way, that Employee entity will contain some of the Contact attributes, but that’s not correct.

So what you actually have to do, to download entities also with specified associated entities?

At first, open the metadata class for the domain service.
Find the Contact navigation property in the Employee entity class. Add [Include] attribute above the property. This way we tell Ria Services to change the query to get Employee also with associated Contact entity.

public Entity<Contact> Contact;

Now change the Domain service class retrieve method to include the Contact.

return this.ObjectContext.Employees.Include("Contact");

One Response to “Enable associated entities to load with base entity”

  1. any luck on this. have the same issue?