Table Valued function and Eager Loading Does not work

Table valued function are nice way to apply further transformations to your linq queries. The reason is, they return IQueryable instead of stored procedure returning IEnumerable. I will not delve into the original problem that I was facing at work, but try to come with an example that identifies the issue I was facing with linq to SQL.

I have a table valued function that simply returns two categories, Beverages and Produce. While I am loading the categories, I also want to eager load Products for those categories as well. On retrieving the categories I simply print those categories to the output screen. Here is an example.

image

image

image

In the above example, I have a table valued function called BvgAndSeaFood that simply returns two categories called Beverages and Produce. In the order to use the table valued function, I go to the linq to SQL designer and drag the function onto the categories table which basically means that the table valued function returns strongly typed instance of categories.  In the query, I am making use of dataloadoptions to turn eager loading. I am saying that while you are loading categories, also load the products for those categories as well. Once I have configured my dataloadoptions I assign the object to the datacontext. Than I am printing the categories to the output screen. Seeing from the results, you would realize that data returned on the screen is incorrect. The results should have been Beverages and Produce not Beverages both times. I simply couldn't figure out why the results that I was getting was incorrect. If you turn off eager loading you get correct results. Here is the changed query.

image

image

Once I removed the eager loading options, the query results returned were correct. This leads me to say that there is something that does not work correctly when you are returning results from a table valued function when eager loading is turned on. After couple of hours of playing around I finally found a work around. Essentially, the categories that I got from the table valued function, I joined them back to categories table and for some reason that fixed the duplicate categories. Here is the changed query.

image

In order to fix the problem I encountered, I simply join the results from the table valued function with categories  collection on the datacontext and returning categories from the categories table.  I consider this a work around, but I really want to know why my original query failed with eager loading turned on. Perhaps readers can shed some light on this matter.

No Comments