tags:

views:

58

answers:

2

I have a fairly complicated join query that I use with my database. Upon running it I end up with results that contain an baseID and a bunch of other fields. I then want to take this baseID and determine how many times it occurs in a table like this:

TableToBeCounted (One to Many)
{
     baseID,
     childID
}

How do I perform a linq query that still uses the query I already have and then JOINs the count() with the baseID?

Something like this in untested linq code:

from k in db.Kingdom
join p in db.Phylum on k.KingdomID equals p.KingdomID
where p.PhylumID == "Something"
join c in db.Class on p.PhylumID equals c.PhylumID
select new {c.ClassID, c.Name};

I then want to take that code and count how many orders are nested within each class. I then want to append a column using linq so that my final select looks like this:

select new {c.ClassID, c.Name, o.Count()}//Or something like that.

The entire example is based upon the Biological Classification system.

Assume for the example that I have multiple tables:

Kingdom
|--Phylum
    |--Class
       |--Order

Each Phylum has a Phylum ID and a Kingdom ID. Meaning that all phylum are a subset of a kingdom. All Orders are subsets of a Class ID. I want to count how many Orders below to each class.

A: 
select new {c.ClassID, c.Name, (from o in orders where o.classId == c.ClassId select o).Count()}

Is this possible for you? Best I can do without knowing more of the arch.

Ryan Bennett
I get this error for the `(from o in orders...)` section: `Error 16 Invalid anonymous type member declarator. Anonymous type members must be declared with a member assignment, simple name or member access.`
Rick
I got the right idea, but the code above will not compile (at least in my situation) It needs to add a a named property: `select new {c.ClassID, c.Name, **Count**=from o in orders where o.classId == c.ClassId select o).Count()}`
Rick
A: 

If the relationships are as you describe:

  var foo = db.Class.Where(c=>c.Phylum.PhylumID == "something")
                    .Select(x=> new { ClassID = x.ClassID, 
                                      ClassName = x.Name, 
                                      NumOrders= x.Order.Count})
                    .ToList();

Side question: why are you joining those entities? Shouldn't they naturally be FK'd, thereby not requiring an explicit join?

p.campbell
I didn't try your code because I got my situation to work, but thanks for the FK stuff. It becomes really easy to traverse through linq. I have a little void in my datatables, with a many-to-many that still requires a join however; which is fine.
Rick