I'm building a linq query using join and into statements.
var testmyquery = from uf in TheFolderModel.UserFolders
where (uf.UserID == TheUserID)
join ul in TheFolderModel.UserBooksheets on
uf.FolderID equals ul.FolderID
join ll in TheFolderModel.BooksheetBooks on
ul.BooksheetID equals ll.BooksheetID
join ua in TheFolderModel.BooksAppointments on
ll.BookID equals ua.BookID
group ua.BookID by uf.FolderID into Holdingvar
orderby Holdingvar.Key
select new { TheCount = Holdingvar.Count(), Holdingvar.Key };
I need to add columns from tables in uf and ul to the retuning object but once I've got a projection on Holdingvar, the intellisense doesn't give me access to uf or ul anymore when I'm in the select new{} statement. How do I add columns in the select statement?
Thanks.
I got it:
var testmyquery = from uf in TheFolderModel.UserFolders
where (uf.UserID == TheUserID)
join ul in TheFolderModel.UserBooksheets on
uf.FolderID equals ul.FolderID
join ll in TheFolderModel.BooksheetBooks on
ul.BooksheetID equals ll.BooksheetID
join ua in TheFolderModel.BooksAppointments on
ll.BookID equals ua.BookID
group ua.BookID by uf.FolderID into Holdingvar
orderby Holdingvar.Key
from uf2 in TheFolderModel.UserFolders
where uf2.FolderID == testg.Key
select new { testk = testg.Count(), testg.Key, uf2.FolderName };
I just needed to redefine a variable after I did the projection in the holding variable.
You can't...once you select new {..., the uf and ul are out of scope.
I'm not sure if this would work for you, but if you need the count and key, you could do a let statement:
var testmyquery = from uf in TheFolderModel.UserFolders
where (uf.UserID == TheUserID)
join ul in TheFolderModel.UserBooksheets on
uf.FolderID equals ul.FolderID
join ll in TheFolderModel.BooksheetBooks on
ul.BooksheetID equals ll.BooksheetID
join ua in TheFolderModel.BooksAppointments on
ll.BookID equals ua.BookID
group ua.BookID by uf.FolderID into Holdingvar
orderby Holdingvar.Key
let someproperty = new { TheCount = Holdingvar.Count(), Holdingvar.Key }
select new { uf.UserID, ........ }
I do this all the time. Why is it not working for you? The structure of my query is a bit different. Perhaps you need to reform it?
var q = (from at in Repository.For<AuditTrailEntity>()
from att in Repository.For<AuditTrailTypeEntity>()
join ue in Repository.For<UserEntity>() on at.UserId equals ue.RowId
join up in Repository.For<UserProfileEntity>() on ue.AspnetUserId equals up.UserId
where (at.AffectedEntityName == "AssetEntity" && at.PKId == assetId.ToString() && at.ActionType == att.RowId)
orderby at.CreatedDate descending
select new AssetAuditTrailModel
{
RowId = at.RowId,
AffectedEntityName = at.AffectedEntityName,
PKId = at.PKId,
ActionType = at.ActionType,
ActionData = at.ActionData,
UserId = at.UserId,
CreatedDate = at.CreatedDate,
ActionName = att.FriendlyName,
UserName = up.FirstName + " " + up.LastName,
});
Related
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.
var CJTDebTransaction = from d in db.DebtorTransactions
join c in db.CarJackaTrackas on d.ProductID equals c.pkfCjtID
join a in db.Agents on c.AgentID equals a.pkfAgentID
join s in db.SalesReps on c.SalesRepId equals s.pkfSrID
where d.TransTypeID==1 && d.Product==1
select new { d.Amount, d.TransTypeID, Name=a.Name.Trim(), a.pkfAgentID,s.pkfSrID,salesrepName=s.Name} into debtRec
group debtRec by new { debtRec.TransTypeID, debtRec.Name, debtRec.pkfAgentID,debtRec.salesrepName,debtRec.pkfSrID} into debtRecGroup
orderby debtRecGroup.Key.Name
select new
{
Sum= debtRecGroup.Sum(model=>model.Amount),
TransTypeId=debtRecGroup.Key.TransTypeID ,
AgentId=debtRecGroup.Key.pkfAgentID,
AgentName=debtRecGroup.Key.Name,
SalesrepId=debtRecGroup.Key.pkfSrID,
SalesRepName=debtRecGroup.Key.salesrepName
};
var WntyDebTransaction = from d in db.DebtorTransactions
join w in db.Warranties on d.ProductID equals w.Id
join a in db.Agents on w.fldAgentID equals a.pkfAgentID
join s in db.SalesReps on w.fldSrId equals s.pkfSrID
where d.TransTypeID == 1 && d.Product == 0
select new { d.Amount, d.TransTypeID, Name=a.Name.Trim(), a.pkfAgentID, s.pkfSrID, salesrepName = s.Name } into debtRec
group debtRec by new { debtRec.TransTypeID, debtRec.Name, debtRec.pkfAgentID, debtRec.salesrepName, debtRec.pkfSrID } into debtRecGroup
orderby debtRecGroup.Key.Name
select new
{
Sum = debtRecGroup.Sum(model => model.Amount),
TransTypeId = debtRecGroup.Key.TransTypeID,
AgentId = debtRecGroup.Key.pkfAgentID,
AgentName = debtRecGroup.Key.Name.Trim(),
SalesrepId = debtRecGroup.Key.pkfSrID,
SalesRepName = debtRecGroup.Key.salesrepName
}
I need to get the output in just one query, i new to linq to entity. i need the result like:- AgentName SalesRepName Debit Total(the total of amount where Product == 0) Credit Total(total of amount where Product==1) Outstanding Total(the difference between Debit Total and Credit Total). any suggestion will be appreciable. thanks in advance :)
I am trying to create an outer join statement in LINQ and am not having much luck. I know that Performing an outer join requires two steps:
(1) Convert the join into a group join with into
(2) Use DefaultIfEmpty() on the group to generate the null value you expect if the joined result set is empty.
I have been using this code as an example:
var query = (from p in dc.GetTable<Person>()
join pa in dc.GetTable<PersonAddress>() on p.Id equals pa.PersonId into tempAddresses
from addresses in tempAddresses.DefaultIfEmpty()
select new { p.FirstName, p.LastName, addresses.State });
So I tried to do this:
var outerJoin =
from h in resultHours
join u in results on h.Key equals u.Key into outer
from dictionary in outer.DefaultIfEmpty()
select new {
The problem is that intellisense doesn't recognize anything in the select new {} statement. I've tried u. and h., even dictionary.
The problem I may be running into is that I'm trying to outer join two dictionaries. It doesn't seem to like that, although this is what I was told I need to do. I am obviously doing something wrong or not understanding something.
I need to join the dictionary results.Unit with the dictionary resultHours.Hours because my output is missing unitId fields under certain conditions. Doing an outer join is supposed to clear this up.
Here is the code for results:
var results =
(from v in VDimUnit
join vf in VFactEnergyAllocation on v.UnitKey equals vf.UnitKey
join vd in VDimGadsEvent on vf.GadsEventKey equals vd.GadsEventKey
join vt in VDimTime on vf.TimeKey equals vt.TimeKey
where typeCodes.Contains(vd.GadsEventTypeCode)
&& vt.YearNum >= (year - 3) && vt.YearNum <= year
group vf by new {v.PlantId, v.PhysicalUnitId, v.NetDependableCapacity, v.NetMaximumCapacity,
vt.MonthNum} into groupItem
select new {groupItem.Key.PlantId, groupItem.Key.PhysicalUnitId, groupItem.Key.NetMaximumCapacity,
groupItem.Key.MonthNum, PO_HRS = groupItem.Sum(
x=> (float)x.AllocatedEnergyMwh / groupItem.Key.NetDependableCapacity),
UO_HRS = groupItem.Sum(x=> (float)x.AllocatedEnergyMwh / groupItem.Key.NetDependableCapacity),
Unit = groupItem.Count(), groupItem.Key}).ToDictionary(x=> x.Key, x=> x);
Here is the code for resultHours:
var resultHours =
(from vt in VDimTime
join vf in VFactEnergyAllocation on vt.TimeKey equals vf.TimeKey
join vd in VDimGadsEvent on vf.GadsEventKey equals vd.GadsEventKey
join v in VDimUnit on vf.UnitKey equals v.UnitKey
group vt by new {v.PlantId, v.PhysicalUnitId, v.NetDependableCapacity, v.NetMaximumCapacity,
vt.MonthNum} into groupItem
select new {groupItem.Key.PlantId, groupItem.Key.PhysicalUnitId, groupItem.Key.NetMaximumCapacity,
Hours = groupItem.Count(), groupItem.Key}).ToDictionary(x=> x.Key.ToString(), x=> x.Hours);
This is presently how I have my output. It will change after I figure out how to do the outer join.
var finalResults =
(from r in results
orderby r.Key.MonthNum, r.Key.PlantId, r.Key.PhysicalUnitId
select new {Site = r.Key.PlantId, Unit = r.Key.PhysicalUnitId, r.Key.MonthNum, Numerator = r.Value.PO_HRS, Denominator =
resultHours[r.Key.ToString()], Weight = r.Key.NetMaximumCapacity, Data_Indicator = DATA_INDICATOR,
Budgeted = budgetedPlannedOutageHrs, Industry_Benchmark = INDUSTRY_BENCHMARK, Comments = comments,
Executive_Comments = executiveComments, Fleet_Exec_Comments = fleetExecComments});
I'm at a loss. The LINQ outer join examples I have found apaprently do not apply when joining dictionaries.
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.
How can i do this ?
where tsc.TransactionID in (from t in Transactions where ........
Eg:
var query = (from tsd in TransactionSampleDetails
join tsc in TransactionSamples on tsd.TransactionSampleID equals tsc.TransactionSampleID
join qp in QualityParameters on tsd.ParameterID equals qp.ParameterID
where tsc.TransactionID in (from t in Transactions where t.StockpileID == 7122 select t.TransactionID)
select new
{
TransactionID = tsc.TransactionID,
ParameterName = qp.Parameter,
ParameterValue = tsd.ActualValue
});
You can use Contains:
where (from t in Transactions
where t.StockpileID == 7122
select t.TransactionID).Contains(tsc.TransactionID)
Mind you, it might be more efficient and appropriate to use another join:
join t in Transactions.Where(t => t.StockpileID == 7122)
on tsc.TransactionId equals t.TransactionID