问题
Assume we have a Menu class that has SubMenus (which is the same type of Menu therefore can have SubMenus and Items too) and Items (which has a different type) and we stored them in two tables(One for Menus and one for Items). Is there any way to load complete graph of the Menu class (all of its SubMenus and Items) using LINQ to SQL?
回答1:
If you define the relationships properly in SQL, LINQToSQL should give you back all of the menus/items with a single query on menus. However, this won't give it back to use as a graph, but as an enumeration of the menus (with related menus and items). You would need to iterate through this enumeration and construct the graph on your own.
On the other hand, you might be able to do something like this:
var roots = db.Menus.Where( m => !m.SubMenus.Count == 0 );
Then, roots would be a collection of the base menus. This might be sufficient if you don't intend to perform any graph analysis algorithms on it, but only intend to traverse it from top to bottom to construct the GUI components.
来源:https://stackoverflow.com/questions/740063/loading-complete-graph-from-sql-using-linq