views:

55

answers:

1

Hi,

I have an entity model and I've been looking to write a linq query that returns counts of children and parents for each grandparent.

I need to output 3 columns: Name of Grandparent | Count of Children | Count of Grandchildren

protected void Page_Load(object sender, EventArgs e)
{
     using (FamilyModel.TheConn myEntities = new FamilyModel.TheConn())
     {
          int TheUserID = 13; // will change later

          var myOutput = from gparents in myEntities.GrandParents
                     where gparents.UserID == TheUserID
                     select gparent.Name, // here's what's missing: the counts

          GridView1.DataSource = myOutput;
          GridView1.DataBind();

     }
}

I've been struggling with SelectMany, Groupby, joins.... I just don't get the result I need for this seemingly simple query. Any input would be greatly appreciated.

Thanks

+2  A: 
var myOutput = from gparent in myEntities.GrandParents
               where gparent.UserID == TheUserID
               select new GrandParentViewModel
               {
                   Name = gparent.Name,
                   ChildrenCount = gparent.Children.Count(),
                   GrandChildrenCount = gparent.Children.SelectMany(c => c.GrandChildren).Count()
               };

That's assuming your Child entity has navigational property GrandChildren (actually the name Children world make more sense here - children of children = grandchildren).

In this case we project onto a GrandParentViewModel:

public class GrandParentViewModel
{
    public string Name { get; set; }
    public int ChildrenCount { get; set; }
    public int GrandChildrenCount { get; set; }
}
Yakimych
The result is unexpected: 1) Name shows "it" (the Intellisense doesn't show the field GparentName), 2) the columns show the same grand total of children and grandchildren in the database and there are 6 rows showing (1 row per grandprent). It should show the name and the count for each grandparent instead of the entire total of children and grandchildren. This is weird.
There were a few typos in the code - I edited them out. Should start with 'from gparent' instead of 'from gparents'. Did you have a variable `gparent` defined anywhere before by chance? Secondly, the `myOutput` variable is a query - if you want the results for one grandparent (the one with `TheUserId`), you need to call `myOutput.FirstOrDefault()`. If you want to retrieve a list of grandparents, call `myOutput.ToList()`.
Yakimych
OH MY GOD IT WORKS!!!!! Thank you sooooo much. I've been struggling with these few lines of code for the last 3 days since I'm new to linq. Your answer will stay in the net for a while because it really solves a problem that I'm sure many struggle with until they figure it out. Thank you very much!!
Glad I could help. Good luck!
Yakimych