Sub Query Where X in (from...? - linq

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

Related

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 to combine two linq to entity queries in just one query?

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 :)

In join want to get not matched records

Work on DF 4 vs 2010.Face problem on join on SalSalesOrderDetail with SalSalesOrderFinancial table.
In SalSalesOrderFinancial one record have SalesOrderDetailID=null. Want to get those records whose SalesOrderDetailID is not present in SalSalesOrderFinancial.
To get desired out put write bellow linq syntax,it’s working .Looking for better join syntax .Is there any way to get desired in one join.
var tempBDwithSODetail = (from p in this.Context.SalSalesOrderFinancials
where p.SalesOrderDetailID != null
select p.SalesOrderDetailID).AsEnumerable();
var tempBDwithOutSODetail = (from p in this.Context.SalSalesOrderFinancials where p.SalesOrderDetailID == null select p).AsEnumerable();
var querySOD = (this.Context.SalSalesOrderDetails.Where(item => !tempBDwithSODetail.Contains(item.SalesOrderDetailID))).AsEnumerable();
var tempBDetail = (from p in querySOD
join q in tempBDwithOutSODetail on p.SalesOrderID equals q.SalesOrderID
where q.SalesOrderDetailID == null
select new
{
q.SalesOrderID,
p.SalesOrderDetailID,
q.CurrencyID,
q.BillingPolicyID,
q.BillTypeID,
q.BillingTypeID
}).AsEnumerable();
If have any query please ask.Thanks in advanced.
if i got you, you just need to simple left join between SalSalesOrderDetail and SalSalesOrderFinancial...
var query = (from u in this.Context.SalSalesOrderDetail
join t in this.Context.SalSalesOrderFinancials
on u.SalesOrderDetailID equals t.SalesOrderDetailID into JoinedList
from t in JoinedList.DefaultIfEmpty()
select new
{
SalSalesOrderDetail = t,
SalSalesOrderFinancials = u
})
.Where(u => u.SalSalesOrderFinancials == null)
.ToList();

LINQ Error when using multiple JOIN in same statement on CRM 2011 Plug-in

Hi I am trying to join multiple entities in CRM 2011 but I get and error saying: {"'xrmsm_sessionEnrollments' entity doesn't contain attribute with Name = 'xrmsm_termsid'."}. That is correct but I am joining the entity that have that attribute.
My Linq Query:
var query2 = from e in svsContext.xrmsm_sessionEnrollmentsSet
join s in svsContext.xrmsm_sessionsSet on e.xrmsm_SessionLookup.Id equals s.xrmsm_sessionsId
join ic in svsContext.xrmsm_institutionCoursesSet on s.xrmsm_institutionCourseLookup.Id equals ic.xrmsm_institutionCoursesId
join ts in svsContext.xrmsm_term_sessionsSet on e.xrmsm_termSessionLookup.Id equals ts.xrmsm_term_sessionsId
join t in svsContext.xrmsm_termsSet on ts.xrmsm_TermLookup.Id equals t.xrmsm_termsId
where (e.xrmsm_StudentLookup.Equals(studentlookup)
&& e.xrmsm_YearLookup.Equals(entity.GetAttributeValue("xrmsm_studentlookup"))
&& ic.xrmsm_institutionCoursesId == institutionCourseGuid
&& t.xrmsm_termsId == termGuid)
select new { sessionName = s.xrmsm_sessionsName, StudentName = e.xrmsm_studentsName, StudentId = e.xrmsm_StudentLookup.Name };
My original SQL query that works on SQL Server:
SELECT en.xrmsm_currentsessionenrollmentsname
,en.xrmsm_isreadonlyname
,en.xrmsm_sessionenrollmentsaverage
,en.xrmsm_sessionenrollmentsgrade
,en.xrmsm_sessionenrollmentsid
,en.xrmsm_sessionenrollments_id
,en.xrmsm_sessionlookup as sessionid
,en.xrmsm_sessionlookupname
,en.xrmsm_sessionsname
,en.xrmsm_studentlookup AS studentid
,en.xrmsm_studentlookupname
,en.xrmsm_studentsname
,en.xrmsm_termsessionlookup
,en.xrmsm_termsessionlookupname
,en.xrmsm_withdrawal
,en.xrmsm_yearaverage
,en.xrmsm_yeargrade
,en.xrmsm_yearlookup
,en.xrmsm_yearlookupname
FROM CoseyTest_MSCRM.dbo.Filteredxrmsm_sessionEnrollments as en INNER JOIN
CoseyTest_MSCRM.dbo.Filteredxrmsm_sessions crmsessions ON
(en.xrmsm_sessionlookup = crmsessions.xrmsm_sessionsid AND en.xrmsm_yearlookup = crmsessions.xrmsm_yearlookup)
INNER JOIN Filteredxrmsm_institutionCourses institutionCourses
on crmsessions.xrmsm_institutioncourselookup = institutionCourses.xrmsm_institutioncoursesid
Inner Join Filteredxrmsm_term_sessions as termsession
on en.xrmsm_termsessionlookup = termsession.xrmsm_term_sessionsid
Inner Join Filteredxrmsm_terms as terms
on termsession.xrmsm_termlookup = terms.xrmsm_termsid
where en.xrmsm_yearlookup = '4BA07BED-3F51-E211-8359-00155D004403'
and en.xrmsm_studentlookup = 'C844AF65-5B51-E211-8359-00155D004403'
and terms.xrmsm_termsid = 'D1D107B7-4551-E211-8359-00155D004403'
and institutionCourses.xrmsm_institutioncoursesid = '2121914E-4551-E211-8359-00155D004403'
Linq provider for CRM has some limitations. You can fount it here. Check if your query violates limitations.
Try having a look at the actual query that it is generating and run that in SQL, it may help understand what is going on.
It could be that something your doing in LINQ is not available in CRM as paramosh mentioned but I can't see anything that jumps out at me.
Thanks for all your responses. I did the following workaround.
Make a query that retrieve a list of all the Student enrollments
Use the Find method of the List<T> class to find if a record exist with the conditions I am searching for.
var query2 = (from e in svsContext.xrmsm_sessionEnrollmentsSet
join s in svsContext.xrmsm_sessionsSet on e.xrmsm_SessionLookup.Id equals s.xrmsm_sessionsId
join ic in svsContext.xrmsm_institutionCoursesSet on s.xrmsm_institutionCourseLookup.Id equals ic.xrmsm_institutionCoursesId
join ts in svsContext.xrmsm_term_sessionsSet on e.xrmsm_termSessionLookup.Id equals ts.xrmsm_term_sessionsId
join t in svsContext.xrmsm_termsSet on ts.xrmsm_TermLookup.Id equals t.xrmsm_termsId
where (e.xrmsm_StudentLookup.Equals(studentlookup))
select new
{
EnrollmentId = e.xrmsm_sessionEnrollments_id,
SessionId = s.xrmsm_sessions_id,
EnrollmentYear = e.xrmsm_YearLookup,
InstitutionCourseId = (Guid)ic.xrmsm_institutionCoursesId,
TermId = (Guid)t.xrmsm_termsId,
Student = e.xrmsm_StudentLookup
}).ToList();
var q = query2.Find(r => r.EnrollmentYear.Id == entity.GetAttributeValue<EntityReference>("xrmsm_yearlookup").Id
&& r.InstitutionCourseId == institutionCourseGuid
&& r.TermId == termGuid);

Outer Join statement in LINQ

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.

Resources