may I ask what's the most efficient way in C# to get parent table data plus children data.
Currently I have a parent table. The parents can have multiple children
CREATE TABLE Parents (
Id INT IDENTITY(1,1) NOT NULL
Name VARCHAR(255)
)
CREATE TABLE Childrens (
Id INT IDENTITY(1,1) NOT NULL
ParentId INT NOT NULL
Name VARCHAR(255)
)
Parent.cs
public int Id {get; set;}
public string Name {get; set;}
public List<Child> Childrens {get; set;}
Child.cs
public int Id {get; set;
public string Name {get; set;}
public int ParentId {get; set;}
Currently I have make multiple database calls. First one gets all the parents. The second one gets all the childrens. Then when all the children returns, it gets added to the parent. I'm wondering is there a way to optimize my sproc or logic call so that I can reduce the number of db calls and reduce the server side operations.
getParents stored procedure
SELECT * FROM Parents
C#
var parents = myContext.Database.SqlQuery<Parent>("getParents");
foreach (var parent in parents)
{
parent.Childrens = myContext.Database.SqlQuery<Parent>($"SELECT * FROM CHILDRENS WHERE ParentId = {parent.Id}").ToList();
}