I have some hierarchical data that I need to return via a stored procedure (because straight LINQ-to-SQL can’t really handle the recursion). Lets say these are the two objects SQLMetal generates that I’m working with:
class TableA_Record
{
public IEnumerable<Child_TableB> Child_TableB_Records;
}
class TableB_Record
{
public TableA_Record parent;
}
Is it possible to create a stored procedure that will return something like an IEnumerable, but also pulls the Child_TableB_Records along with it and populates those as well? Kind of similar to what would happen in this code, but using a stored procedure:
using(DataContext db = new DataContext())
{
DataLoadOptions dlOptions = new DataLoadOptions();
dlOptions.LoadWith<TableA_Record>(x => x.Child_TableB_Records);
db.loadOptions = dlOptions;
var query = from a in db.TableA
select a;
}
Any examples or links to tutorials would be highly appreciated if this is possible. Thanks in advance!
I don’t believe what you are trying to achieve is possible with Linq2Sql.
However a possible work around would be to use the
IMultiResultinterface. So you would set up your stored procedure to return two sets of results (TableA_Record and TableB_Records). You add the stored procedure to the DBML and alter the call to the stored procedure to be cast asIMultiResultand depending on the attributes you decorate the method with the Linq results will be populated in those objects.There is an example of this by Scott Gu LINQ to SQL (Part 6 – Retrieving Data Using Stored Procedures) (Section named “Handling Multiple Result Shapes from stored procedures”)
You would then have to take an additional step and map the objects into the structure that you are looking for.
There are additional steps that you need to take but I believe this is closest to what you are trying to achieve as you return one set of results that you are then working with.
Edit:
One thing to note is the ordering of the
ResultTypeattribute is important. The order result sets are returned is the order that theResultTypeattribute should be used to decorate the method. If you get the ordering incorrect the objects will just return as null and no exception will be thrown (I have had issues with this happening before).Here are some additional examples: