I have two tables that I want to fetch data from.
Lets call them “Parent” and “Children”. The “Parent” table has many records in the “Children” table. (One to Many)
My problem is I want to find an efficient method for displaying the data the two tables contain to my ASP.NET MVC application. My approach is to select all records from “Parent” then loop through each one selecting the data from “Children”.
So I need help designing a query for SQL Server 05 that can get the data out for C# more efficiently, I was planning of creating type classes and the “Parent” class would have a “List” that in my View I can loop through outputting the values.
public class Parent_Type
{
public string Name { get; set; }
public List<Children_Type> Children { get; set; }
}
public class Children_Type
{
public string Name { get; set; }
}
The data needs to be displayed like: (The name of the “Parent” record then a list of “Children” records”)
“Parent 123”
- “Child 1”
- “Child 2”
- “Child 3”
“Parent 124”
- “Child 1”
- “Child 2”
- “Child 3”
I’d pull all of the data at once and then run through it programmatically.
When you get the data back, the parents will be repeated so you’ll need to filter it down. You could do this via LINQ by providing a parent comparison or via a for loop. Itereate through the list collapsing on unique parent as each record will, in fact, represent a child or a childless parent.
Information about LINQ’s “distinct” is available here.