Using GroupBy in Linq complex - linq

Here is my table structure
table1 - PLAYER
PlayerID
FirstName
LastName
EmailAddress
CellNo
Table2 - Team
TeamID
TeamName
Table3 - TEAMPLAYERS
ID
PlayerID
TeamID
A player can be part of more than one team.
Question:
Now I want to get the player basic details along with the count of no. of teams he plays for. I use the following query to get the result in SQL:
SELECT P.FirstName, P.LastName, P.EmailAddress, P.CellNo, COUNT(TP.TeamID)
FROM Player P
JOIN TeamPlayer TP ON P.PlayerID = TP.PlayerID
GROUP BY P.PlayerID, P.FirstName, P.Lastname, P.EmailAddress, P.CellNo;
This works perfectly.
However, im stuck when converting this to linq. Not much of help from online resources. Can someone help me with this?

Database Contexts dbContext.Players and dbContext.TeamPlayers are just representational, check your project for right context
var result= (from player in dbContext.Players
join teamPlayer in dbContext.TeamPlayers
on player.PlayerID equals teamPlayer.PlayerID
select new{player,teamPlayer})
.GroupBy(P=>new
{
P.PlayerID,
P.FirstName,
P.Lastname,
P.EmailAddress,
P.CellNo
})
.Select(x=>new
{
x.Key.FirstName,
x.Key.LastName,
x.Key.EmailAddress,
x.Key.CellNo,
TeamIDCount=x.Count(z=>z.teamPlayer.TeamID)
}).ToList();

Related

Entity Framework Query select hard-coded user created column

I'm creating a select from multiple tables using a union as I need to return a list of activities that has occurred for a particular client on the database. I need to return each union with an added column so I can tell the difference between the results. If I was to do the query in SQL it would look something like this:
SELECT cn.NoteID, cn.Note, cn.InsertedDate, 'Note Added' Notes
FROM Client c
INNER JOIN ClientNotes cn ON cn.ClientID = c.ID
WHERE c.ClientID = #ClientID
UNION
SELECT rc.ID, rc.CommNote, rc.InsertedDate, 'Communication Added' Notes
FROM ReceivedCommunication rc
LEFT JOIN Job j ON j.ID = rc.JobID
WHERE j.ClientID = #ClientID or rc.ClientID = #ClientID
My Question is how in Entity Framework using IQuerable do I return the hard-coded Notes column?
I have something like this so far:
Dim client as IQueryable(Of myresultclass) =
(From c As Client
Join cn As ClientNotes In ClientCompanyNotes On c.ID Equals cn.ClientID
Where c.ClientID = ClientID
Select cn.NoteID, cn.Note, cn.InsertedDate).Union(
From rc As ReceivedCommunication In ReceivedCommunications
Join j As Job In Jobs On j.ID Equals rc.JobID
Where j.ClientID = ClientID or rc.ClientID = ClientID
Select rc.ID, rc.CommNote, rc.InsertedDate)
Thanks for your help
Ok worked it out, should have been obvious. For anyone with the same issue, I had to update my Select from Select cn.NoteID, cn.Note, cn.InsertedDate to:
Select New myresultclass With {
.ActivityID = cn.NoteID,
.ActivityType = "Note Added"
.InsertedDate = cn.InsertedDate
}
for each one of the unions that I had
Thanks

Linq left outer group by, then left outer the group

I've this query that i'm trying to put as linq:
select *
from stuff
inner join stuffowner so on so.stuffID = stuff.stuffID
left outer join (select min(loanId) as loanId, stuffownerId from loan
where userid = 1 and status <> 2 group by stuffownerId) t on t.stuffownerid = so.stuffownerid
left outer join loan on t.LoanId = loan.LoanId
when this is done, I would like to do a linq Group by to have Stuff has key, then stuffowners + Loan as value.
I can't seem to get to a nice query without sub query (hence the double left outer).
So basically what my query does, is for each stuff I've in my database, bring the owners, and then i want to bring the first loan a user has made on that stuff.
I've tried various linq:
from stuff in Stuffs
join so in StuffOwners on stuff.StuffId equals so.StuffId
join tLoan in Loans on so.StuffOwnerId equals tLoan.StuffOwnerId into tmpJoin
from tTmpJoin in tmpJoin.DefaultIfEmpty()
group tTmpJoin by new {stuff} into grouped
select new {grouped, fluk = (int?)grouped.Max(w=> w.Status )}
This is not good because if I don't get stuff owner and on top of that it seems to generate a lot of queries (LinqPad)
from stuff in Stuffs
join so in StuffOwners on stuff.StuffId equals so.StuffId
join tmpLoan in
(from tLoan in Loans group tLoan by tLoan.StuffOwnerId into g
select new {StuffOwnerId = g.Key, loanid = (from t2 in g select t2.LoanId).Max()})
on so.StuffOwnerId equals tmpLoan.StuffOwnerId
into tmptmp from tMaxLoan in tmptmp.DefaultIfEmpty()
select new {stuff, so, tmptmp}
Seems to generate a lot of subqueries as well.
I've tried the let keyworkd with:
from tstuffOwner in StuffOwners
let tloan = Loans.Where(p2 => tstuffOwner.StuffOwnerId == p2.StuffOwnerId).FirstOrDefault()
select new { qsdq = tstuffOwner, qsdsq= (int?) tloan.Status, kwk= (int?) tloan.UserId, kiwk= tloan.ReturnDate }
but the more info i get from tLoan, the longer the query gets with more subqueries
What would be the best way to achieve this?
Thanks

TSQL equivalent of Linq SelectMany

I would like the resultset that consists of the union of queries performed based on each row of an outer SELECT query. How do I do this?
As an example:
create table Person
(
Id int,
Age int
)
create table Movie
(
Id int,
Title varchar(500),
AgeRestriction int
)
I would like a resultset that shows me, for every person, which movies that person would be allowed to watch.
UPDATE: Ok, so as it turns out there is no "equivalent" of SelectMany in TSQL since the model is completely different, as the author of the correct answer has pointed out an inner join will do the job just fine.
Your question is pretty unclear but it sounds like you might want CROSS APPLY
Random Example
SELECT DISTINCT ca.* /*DISTINCT for UNION semantics*/
FROM master..spt_values v
CROSS APPLY (SELECT TOP 2 *
FROM sys.columns c
WHERE c.name > v.name
ORDER BY c.name) ca
Edit. Following clarification you just need a JOIN
SELECT P.Id,
M.Title
FROM Person P
JOIN Movie M
ON M.AgeRestriction <= P.Age

Dynamics CRM 2011 - Filtering LINQ query with outer joins

I have a requirement to query for records in CRM that don't have a related entity of a certain type. Normally, I would do this with an Left Outer Join, then filter for all the rows that have NULLs in the right-hand side.
For example:
var query = from c in orgContext.CreateQuery<Contact>()
join aj in orgContext.CreateQuery<Account>()
on c.ContactId equals aj.PrimaryContactId.Id
into wonk
from a in wonk.DefaultIfEmpty()
where a.Name == null
select new Contact
{
FirstName = c.FirstName,
LastName = c.LastName,
};
This should return me any Contats that are not the Primary Contact of an account. However, this query ends up returning all contacts...! When you look at the SQL that gets generated in SQL Profiler it comes out like this:
SELECT cnt.FirstName, cnt.LastName
FROM Contact as cnt
LEFT OUTER JOIN Account AS acct
ON cnt.ContactId = acct.PrimaryContactId AND acct.Name is NULL
So, I get the Left Join OK, but the filter is on the Join clause, and not in a WHERE clause.and not as it should, like this:
SELECT cnt.FirstName, cnt.LastName
FROM Contact as cnt
LEFT OUTER JOIN Account AS acct
ON cnt.ContactId = acct.PrimaryContactId
WHERE acct.Name is NULL
Clearly, the results from this query are very different! Is there a way to get the query on CRM to generate the correct SQL?
Is this a limitation of the underlying FetchXML request?
Unfortunately, this is a limitation of CRM's LINQ and FetchXML implementations. This page from the SDK states outer joins are not supported:
http://technet.microsoft.com/en-us/library/gg328328.aspx
And while I can't find an official document, there are a lot of results out there for people mentioning FetchXML does not support left outer joins, for example:
http://gtcrm.wordpress.com/2011/03/24/fetch-xml-reports-for-crm-2011-online/
Try this:
var query = from c in orgContext.CreateQuery<Contact>()
where orgContext.CreateQuery<Account>().All(aj => c.ContactId != aj.PrimaryContactId.Id)
select new Contact
{
FirstName = c.FirstName,
LastName = c.LastName,
};
If you don't need to update the entity (e.g. to process all the corresponding validation rules and workflow steps), you can write less-ugly and more efficient queries by hitting the SQL Server directly.
Per CRM's pattern, the views take care of most of the common joins for you. For instance, the dbo.ContactBase and dbo.ContactExtensionBase tables are already joined for you in the view dbo.Contact. The AccountName is already there (called AccountIdName for some bizarre reason, but at least it's there).

Linq query help

I'm attempting to write a linq query which uses several tables of related data and have gotten stuck.
The expected result: I need to return the three most populous metropolitan areas per region by population descending.
tables w/sample data:
MetroAreas -- ID, Name
2, Greater New York
Cities -- ID, Name, StateID
1293912, New York City, 10
CityPopulations -- ID, CityID, CensusYear, Population
20, 1293912, 2008, 123456789
21, 1293912, 2007, 123454321
MetroAreaCities -- ID, CityID, MetroAreaID
1, 1293912, 2
States -- ID, Name, RegionID
10, New York, 5
Regions -- ID, Name
5, Northeast
I start with the metro areas. Join the MetroAreaCities to get city IDs. Join Cities to get state IDs. Join States to get the region ID. Join regions so I can filter with a where. I get stuck when I try to include CityPopulations. I only want the three most populous metro areas for a given region. Doing a simple join on the cityPopulations returns a record per year.
(Here's what I have so far, this query was written for SubSonic 3):
return from p in GeoMetroArea.All()
join q in GeoMetroAreaCity.All() on p.ID equals q.MetroAreaID
join r in GeoCity.All() on q.CityID equals r.ID
join s in GeoState.All() on r.StateID equals s.ID
join t in GeoRegion.All() on s.RegionID equals t.ID
where t.ID == regionObjectPassedToMethod.ID
select p;
Can anyone help me with this query or point me in the right direction? Thank you very very much.
I haven't compiled it, but this should get you close:
var regionID = 5;
var year = (from c in GeoCityPopulation.All()
select c.CensusYear
).Max();
var metros =
// States in Region
from s in GeoStateAll()
where s.RegionID == regionID
// Cities in State
join c in GeoCity.All() on s.CityID equals c.ID
// Metro Area for City
join mc in GeoMetroAreaCity.All() on c.ID equals mc.CityID
// Population for City
join cp in GeoCityPopulation.All() on c.ID equals cp.CityID
where cp.CensusYear = year
// Group the population values by Metro Area
group cp.Population by mc.MetroAreaID into g
select new
{
MetroID = g.Key, // Key = mc.MetroAreaID
Population = g.Sum() // g = seq. of Population values
} into mg
// Metro for MetroID
join m in GeoMetroArea.All() on mg.MetroID equals m.ID
select new { m.Name, mg.Population };

Resources