LINQ 2 lefts joins with Sum - linq

I am trying to do a relatively straight forward SQL query with linq:
SELECT ir.resource_id, r.first_name, r.surname, rt.job_title, SUM(plan_ts_hours), SUM(ts_hours) FROM tbl_initiative_resource ir
INNER JOIN tbl_resource r ON ir.resource_id = r.resource_id
INNER JOIN tbl_resource_type rt ON rt.resource_type_id = r.resource_type_id
LEFT JOIN tbl_plan_timesheet pts on pts.resource_id = ir.resource_id AND pts.initiative_id = ir.initiative_id
LEFT JOIN tbl_timesheet ts on ts.resource_id = ir.resource_id AND ts.initiative_id = ir.initiative_id
WHERE ir.initiative_id = 111
GROUP BY ir.resource_id, r.first_name, r.surname, rt.job_title
After reading this blog: http://smehrozalam.wordpress.com/2010/04/06/linq-how-to-build-complex-queries-utilizing-deferred-execution-and-anonymous-types/
I came up with the following linq:
var query = (from initRes in Context.tbl_initiative_resource
join res in Context.tbl_resource on initRes.resource_id equals res.resource_id
join resType in Context.tbl_resource_type on res.resource_type_id equals resType.resource_type_id
from tsheet in Context.tbl_timesheet.Where(x => x.resource_id == initRes.resource_id).Where(x => x.initiative_id == initRes.initiative_id).DefaultIfEmpty()
from plannedtsheet in Context.tbl_plan_timesheet.Where(x => x.resource_id == initRes.resource_id).Where(x => x.initiative_id == initRes.initiative_id).DefaultIfEmpty()
where initRes.initiative_id == initiativeID
group new { ID = res.resource_id, ResourceType = resType.job_title, Times = tsheet, P = plannedtsheet } by initRes.resource_id into g
select new
{
ResourceID = g.Key,
Hours = g.Sum(x => (decimal?)x.Times.ts_hours),
PlannedHours = g.Sum(x => (decimal?)x.P.plan_ts_hours)
}).ToList();
Any ideas on how I can access the ResourceType when selecting the new anonymous type?

ResourceType is part of the the grouping key, so g.Key.ResourceType should do it.
(Check out the type of ResouceID in the results, as you've assigned it g.Key it will be an instance of the (anonymous) type created in the group clause.

Related

How write count(ColumnName) in LINQ?

Hi everyone I need help write below query in LINQ
select zProcessStatus.StatusName, zProcessStatus.StatusNameDari, COUNT( ProcessProgress.SchoolID) as 'Count'
from zProcessStatus
left join ProcessProgress on ProcessProgress.ProcessStatusID=zProcessStatus.ProcessStatusID
join SubProcessStatus on zProcessStatus.ProcessStatusID=SubProcessStatus.ProcessStatusID
where SubProcessStatus.SubProcessID='18250478-7DA5-45D6-90A7-51DFE94B09C8'
group by zProcessStatus.StatusName
,zProcessStatus.StatusNameDari
I have written it as below, it's not give the expected result same as SQL query
(from zProcessStatus in _applicationContext.ZProcessStatus
join processProgress in _applicationContext.ProcessProgress on zProcessStatus.ProcessStatusId equals processProgress.ProcessStatusId into processprogressGroup
from a in processprogressGroup.DefaultIfEmpty()
join subProcessStatus in _applicationContext.SubProcessStatus on zProcessStatus.ProcessStatusId equals subProcessStatus.ProcessStatusId
where subProcessStatus.SubProcessId == subprocessid
select new
{
SchoolId = a.SchoolId.ToString(),
StatusNameDari = zProcessStatus.StatusNameDari,
StatusName = zProcessStatus.StatusName,
}).Distinct().ToList().GroupBy(x => new { x.StatusNameDari, x.StatusName, x.SchoolId }).Select(
g => new
{
g.Key.StatusNameDari,
g.Key.StatusName,
Count = g.Count()
}).ToList();

how use multiple join in linq?

var abc1 = from dlist in db.DebtorTransactions.ToList()
join war in db.Warranties on dlist.ProductID equals war.Id
join ag in db.Agents on war.fldAgentID equals ag.pkfAgentID
join sr in db.SalesReps on war.fldSrId equals sr.pkfSrID
where dlist.TransTypeID == 1
select new
{
dlist.Amount,
dlist.TransTypeID,
name = ag.Name,
ag.pkfAgentID,
sr.pkfSrID,
salesnam = sr.Name
} into objabc
group objabc by new
{
objabc.TransTypeID,
objabc.name,
objabc.salesnam,
objabc.Amount
};
var amt1 = abc1.Sum(x => x.Key.Amount);
var abc2 = from dlist in db.DebtorTransactions.ToList()
join cjt in db.CarJackaTrackas on dlist.ProductID equals cjt.pkfCjtID
join ag in db.Agents on cjt.AgentID equals ag.pkfAgentID
join sr in db.SalesReps on cjt.SalesRepId equals sr.pkfSrID
where dlist.TransTypeID == 0
select new
{
dlist.Amount,
dlist.TransTypeID,
name = ag.Name,
ag.pkfAgentID,
sr.pkfSrID,
enter code here` salesnam = sr.Name
} into objabc
group objabc by new
{
objabc.TransTypeID,
objabc.name,
objabc.salesnam,
objabc.Amount
};
var amt2 = abc1.Sum(x => x.Key.Amount);
//var result1=
return View();
i am new to linq, this query is working but i need to get the sum of Amount where dlist.TransTypeID == 0 and where dlist.TransTypeID == 1 by just single query. may anybody help me? thanks in advance
Here's a trimmed down example of how you can do it. You can add the joins if they are necessary, but I'm not clear on why you need some of the extra join values.
var transTypeAmountSums = (from dlist in db.DebtorTransactions
group dlist by dlist.TransTypeId into g
where g.Key == 0 || g.Key == 1
select new
{
TransTypeId = g.Key,
AmountSum = g.Sum(d => d.Amount)
}).ToDictionary(k => k.TransTypeId, v => v.AmountSum);
int transTypeZeroSum = transTypeAmountSums[0];
int transTypeOneSum = transTypeAmountSums[1];
A couple of things to note:
I removed ToList(). Unless you want to bring ALL DebtorTransactions into memory then run a Linq operation on those results, you'll want to leave that out and let SQL take care of the aggregation (it's much better at it than C#).
I grouped by dlist.TransTypeId only. You can still group by more fields if you need that, but it was unclear in the example why they were needed so I just made a simplified example.

How can I get the top categories by join in LINQ?

I am working on classified ads project I am facing problem to get top categories where most ads are posted every category have sub category also.
I made query but it is working for sub category ads I want if any category have no sub category then parent category ads should counted.
var result = (from c in db.Category
join a in db.Ad on c.CategoryId equals a.CategoryId
where c.ParentId != null
group c by c.ParentId into g
select new { cat = g.Key, a = g.Count() })
.OrderBy(c => c.cat)
.OrderByDescending(a => a.a);
My Category Table is like this
CategoryId ----- ParentId -----Name
How can I do this?
I guess this could be done with separate queries:
Get a list of categories that don't have any parentId set:
var resultsWithoutSubs = from c in db.Category
where c.ParentId == null
&& !result.Any(r => cat == c.CategoryId)
select c;
Based on the list above, repeat the original query:
var counts = from c in resultsWithoutSubs
join a in dbAd on c.CategoryId equals a.CategoryId
group c by c.CategoryId into g
select new {cat = g. Key, a = g.Count};
Then you should be able to Union these the first and the last list and sort the results.
Try this:
var results = db.Category
.Join(db.Ad, cat => cat.CategoryId,
ad => ad.CategoryId, (cat, ad) => new { cat, ad } )
.Where (c => !dbCategory
.Any (d => c.cat.CategoryId == d.ParentId) && c.cat.ParentId == null)
.GroupBy (c => c.cat.CategoryId)
.Select (g => new
{ cat = g.Key, a = g.Count () }
);

Doing 2 Left Joins on the same table with one call

I have the following tables:
Users:
userId, userFirstName, userLastName.
holdBilling:
bEntityID, CarrierOID, PayerOID, holdTYPE, createUserID.
carrier:
carrierOID, carrierName.
payer:
payerOID, payerName.
I want the code to save in a new entity
holdBilling => new
{
FirstName, LastName, CarrierName, PayerName
}
One of these Entities has either a payer or a carrier value (cannot have both). Basically i want to make 2 left joins on the same table with one call. This would be the SQL query that would work for me.
SELECT TOP 1000 [ID]
,[bEntityID]
,c.carrierID
,c.carrierName
,p.payerID
,p.payerName
,[holdType] ( this is "C" for carrier and "P" for payer )
FROM .[dbo].[holdBilling] hb
left join dbo.payer p on hb.payerID = p.payerID
left join dbo.carrier c on hb.carrierID = c.carrierID
where [bEntityID] = 378
The temporary solution I've found is getting a list of all Carriers
var listC = (from hold in holdBilling
join u in Users on hold.createUserID equals u.userID
join c in carrier.DefaultIfEmpty() on hold.carrierID equals c.carrierID
select new
{
Elem = hold,
FName = u.userFirstName,
LName = u.userLastName,
Carrier = c.carrierName,
Payer = ""
}).ToList();
and one for all payers
select new
{
Elem = hold,
FName = u.userFirstName,
LName = u.userLastName,
Carrier = "",
Payer = p.payerName
}).ToList();
and merging the two,I'm confident there has to be a solution for doing both in one query.
Something like this maybe:
var listC = (
from hb in holdBilling
from p in payer.Where(a=>a.payerID==hb.payerID).DefaultIfEmpty()
from c in carrier.Where(a=>a.carrierID=hb.carrierID).DefaultIfEmpty()
where hb.bEntityID==378
select new
{
hb.bEntityID,
c.carrierID,
c.carrierName,
p.payerID,
p.payerName,
holdType=(payer==null?"P":"C")
}
).Take(1000)
.ToList();
You need to use DefaultIfEmpty to do a left join
var listC = (from hold in holdBilling
from u in Users.Where(x => hold.createUserID == x.userID).DefaultIfEmpty()
from c in carrier.Where(x => hold.carrierID == x.carrierID).DefaultIfEmpty()
select new
{
Elem = hold,
FName = u.userFirstName,
LName = u.userLastName,
Carrier = c.carrierName,
Payer = ""
}).ToList();

Linq left outer join across multiple tables retrieving info from each table

I am new to linq and want to perform joins across three tables. The sql equivalent of what I am trying to do is:
SELECT PM.Id, PM.new_clientId, .....
C.new_firstname, c.new_surname,.....
A.new_addressid, A.new_addressline1, A.new_addressline2.....
CY.new_county
FROM partialMatch PM
INNER JOIN new_client C ON PM.new_clientId = C.new_clientId
LEFT OUTER JOIN new_address A ON C.new_addressId = A.new_addressId
LEFT OUTER JOIN new_county CY ON A.new_countyId = CY.new_countyId
WHERE PM.ownerId = #UserId AND PM.new_reviewed <> true
The linq code I have developed is this, but these don't seem to be outer join as it is not returning any results unless I comment out the joins to the address and county table
var partialMatches = from pm in ContextService.CreateQuery<new_partialmatch>()
join c in ContextService.CreateQuery<new_client>() on pm.new_ClientId.Id equals c.new_clientId
join a in ContextService.CreateQuery<new_address>() on c.new_AddressID.Id equals a.new_addressId
join cy in ContextService.CreateQuery<new_county>() on a.new_CountyID.Id equals cy.new_countyId
where pm.OwnerId.Id == _currentUserId && pm.new_Reviewed != true
select new
{
Id = pm.Id,
new_ClientID = pm.new_ClientId,
new_MatchingCRMClientID = pm.new_MatchingCRMClientId,
new_MatchingVulcanClientID = pm.new_MatchingVulcanClientID,
new_name = pm.new_name,
firstname = c.new_FirstName,
surname = c.new_Surname,
dob = c.new_DateOfBirth,
addressId = a.new_addressId,
address1 = a.new_AddressLine1,
address2 = a.new_AddressLine2,
address3 = a.new_AddressLine3,
address4 = a.new_AddressLine4,
county = cy.new_County
};
Any help would be greatly appreciated,
Thanks,
Neil
EDIT:
I also tried using the 'into' statement but then on my second join the alias isn't recognised.
from pm in ContextService.CreateQuery<new_partialmatch>()
join c in ContextService.CreateQuery<new_client>() on pm.new_ClientId.Id equals c.new_clientId into pmc
from x in pmc.DefaultIfEmpty()
join a in ContextService.CreateQuery<new_address>() on c.new_AddressID.Id equals a.new_addressId
So for the c.newIddressID.Id equals a.new_addressId I get this error message:
The name 'c' is not in scope on the left side of 'equals'. Consider swapping the expressions on either side of 'equals'.
var addressCountryQuery = from a in ContextService.CreateQuery<new_address>()
from cy in ContextService.CreateQuery<new_county>().Where( cy => cy.new_countyId == a.new_CountyID.Id).DefaultIfEmpty()
select new
{
addressId = a.new_addressId,
address1 = a.new_AddressLine1,
address2 = a.new_AddressLine2,
address3 = a.new_AddressLine3,
address4 = a.new_AddressLine4,
county = cy.new_County
}
var partialMatches = from pm in ContextService.CreateQuery<new_partialmatch>()
join c in ContextService.CreateQuery<new_client>() on pm.new_ClientId.Id equals c.new_clientId
from a in addressCountryQuery .Where( a => a.addressId == c.new_AddressID.Id).DefaultIfEmpty()
where pm.OwnerId.Id == _currentUserId && pm.new_Reviewed != true
select new
{
Id = pm.Id,
new_ClientID = pm.new_ClientId,
new_MatchingCRMClientID = pm.new_MatchingCRMClientId,
new_MatchingVulcanClientID = pm.new_MatchingVulcanClientID,
new_name = pm.new_name,
firstname = c.new_FirstName,
surname = c.new_Surname,
dob = c.new_DateOfBirth,
addressId = a.addressId,
address1 = a.AddressLine1,
address2 = a.AddressLine2,
address3 = a.AddressLine3,
address4 = a.AddressLine4,
county = a.County
};
See how I modified the join for a and cy so I could add the DefultIfEmpty method.
I split the two outer joins in to one query and then join that query back into the original query.

Resources