I have need to select a number of ‘master’ rows from a table, also returning for each result a number of detail rows from another table. What is a good way of achieving this without multiple queries (one for the master rows and one per result to get the detail rows).
For example, with a database structure like below:
MasterTable: - MasterId BIGINT - Name NVARCHAR(100) DetailTable: - DetailId BIGINT - MasterId BIGINT - Amount MONEY
How would I most efficiently populate the data object below?
IList<MasterDetail> data; public class Master { private readonly List<Detail> _details = new List<Detail>(); public long MasterId { get; set; } public string Name { get; set; } public IList<Detail> Details { get { return _details; } } } public class Detail { public long DetailId { get; set; } public decimal Amount { get; set; } }
Normally, I’d go for the two grids approach – however, you might also want to look at FOR XML – it is fairly easy (in SQL Server 2005 and above) to shape the parent/child data as xml, and load it from there.
Also – LINQ-to-SQL supports this type of model, but you need to tell it which data you want ahead of time. Via DataLoadOptions.LoadWith:
If you don’t use
LoadWith, you will get n+1 queries – one master, and one child list per master row.