I was experiencing some performance issues in my Silverlight application and got it narrowed down to the mapping of the domain objects. After running SQL profiler and doing some research I figured out that it was due to Linq lazy loading.
As an example if I have the following data structure:
I would have an “EmployeePosition” domain object and an “Employee” domain object. I will use the following Linq statement to bring back all Employee Positions:
When executing above code, there is a separate call made to the database to get the “FirstName” then another call to get the “LastName” for each of the “EmployeePosition” objects due to LINQ lazy loading (default). So if I have 10 employee positions, there are 20 additional calls made to the database.
There are a few solutions to solve this issue:
- Disable lazy loading for the entire dbml file.
- Specify “DataLoadOptions” on the Data Context. This is a valid option if you do not re-use the Data Context.
- Use projection to load only necessary data.
The best option for my situation was to use projection to load my data. To do this I extended my existing Employee domain object by creating a partial “Employee” class and adding a string “Position” property. Then I used projection to load my data to the Employee domain object.
When I executed above code I got the following run-time error:
Explicit construction of entity type ‘Employee’ in query is not allowed.
After doing a little research I discovered that projection to a domain object is not allowed. As a work around, I used my “EmployeeWithPosition” custom object which only contains properties that I am interested in from the “Employee” and “EmployeePosition” domain objects to project my data.