INNER JOIN LEFT JOIN in LINQ to SQL - sql

How to convert INNER JOIN and LEFT JOIN in the following SQL query to LINQ to SQL? Thanks!
SELECT transactions.postdate,
transactions.clientkey AS TransClientKey,
transactions.type AS TransType,
clients.clientno,
Isnull(clients.nostmt, 0) AS CliNoStmt,
Isnull(aging.nostmt, 0) AS AgeNoStmt,
pmtchecks.*
FROM ((pmtchecks
INNER JOIN transactions
ON pmtchecks.transkey = transactions.transkey)
INNER JOIN clients
ON transactions.clientkey = clients.clientkey)
LEFT JOIN aging
ON ( transactions.clientkey = aging.clientkey )
AND ( pmtchecks.debtorkey = aging.debtorkey )
WHERE ( pmtchecks.debtorkey = 36927 )
AND ( transactions.status = 0 )
AND ( transactions.postdate <= '31-May-2012' )
AND ( ( transactions.postdate >= '01-May-2012' )
OR ( clients.clientno = 'UNKNOWN' ) )
ORDER BY pmtchecks.checkdate,
pmtchecks.checkno

Hi this is kind of dummy code i cnt say its exactly right but the idea will be exactly same to get the result
var anonymousType= (from pm in pmtchecks
join tr in transactions
on pm.transkey equals tr.transkey //INNERJOIN
join cl in clients
on tr.clientKey equals cl.clientKey
join ag in aging
on pm.debtorkey equals ag.debtorKey into ljoin //Left Join
from lj in ljoin.DefaultOrEmpty()
where pm.debortkey==36927 && tr.status==0 && tr.postdate<="31-May-2012" && tr.postdate>="01-May-2012" //u will have to change this to date format first
Select new {PostDate=tr.postdate, TransClientKey=tr.clientkey,TransType=tr.type,ClientNo=cl.clientno,CliNoStmt=cl.nomst ?? 0,AgeNoStmt=ag.nomst ??0,Pmtchecks=pm } //Anonymous type from this you can extract the values and fill to your custom type
).OrderBy(o=>o.Pmtchecks.checkdate).OrderBy(o=>o.Pmtchecks.checkno).ToList();
Hope this will help.

LINQ Query Samples
EDITED
var pmtchecks = from p in urcontext.pmtchecks
join t in urcontext.transactions on p.transkey equals t.transkey
join a in urcontext.aging on t.clientkey equals a.clientkey into details
from d in details.Where( a => ( a.debtorkey == p.debtorkey)).DefaultIfEmpty()
where (p.debtorkey == 36927 && t.status == 0 && t.postdate <= '31-May-2012'
&& (t.postdate >= '01-May-2012' || c.clientno == 'UNKNOWN' ))
orderby p.checkdate, p.checkno
select new
{
t.postdate,
t.clientkey,
// TransClientKey = t.clientkey, //only works if TransClientKey is property
t.type ,
//TransTypet = t.type ,//property
c.clientno,
c.nostmt,
//CliNoStmt = c.nostmt ?? 0,//property
a.nostmt//,
//AgeNoStmt = nostmt ?? 0,//property
//p. ... //follow above for p columns
};

Related

Database query - unusual query

I'm trying to transfer a query to LINQ
It's a bit complicated and I don't know if I'm doing the right thing
There is also a problem with SELECT to save it properly
SQL QUERY:
SELECT ISNULL(SUM(1),0) TotalSubmitted,
ISNULL(SUM(CASE WHEN Pic.PhotoFileName IS NULL THEN 0 ELSE 1 END),0) TotalAssigned
FROM tblFromPhone Ph
INNER JOIN tblOfficer O ON Ph.OfficerCode = O.Code
OUTER APPLY(SELECT PhotoFileName FROM tblPhotos P
WHERE P.validityTo IS NULL
AND P.PhotoFileName = Ph.DocName
AND P.OfficerID = O.OfficerID)Pic
WHERE CAST(Ph.LandedDate AS DATE) BETWEEN #FromDate AND #ToDate
AND O.ValidityTo IS NULL
AND DocType = N'E'
AND OfficerCode = #OfficerCode
My LINQ:
var res = (from FP in context.TblFromPhone
join O in context.TblOfficer on FP.OfficerCode equals O.Code
join P in context.TblPhotos on FP.DocName equals P.PhotoFileName into P
from Ph in P.Where(x => x.OfficerId == O.OfficerId).DefaultIfEmpty()
where Ph.ValidityTo == null
where FP.LandedDate >= DateTime.Parse(fromDate)
&& FP.LandedDate <= DateTime.Parse(toDate)
&& O.ValidityTo == null
&& FP.DocType == "E"
&& FP.OfficerCode == officerCode
select new EnrolmentModel()
{
TotalSubmitted = // How to make?
TotalAssigned = // How to make?
})
.FirstOrDefault();

join, group by and count sql to linq conversion

Query:
SELECT COUNT(*) as Avalied
FROM LeaveMaster as lm
JOIN LeaveSubsidary as ls
ON lm.TransMasterId = ls.TransMasterId
WHERE lm.SystemCode = 'abc123' AND lm.EmployeeCode = '0014' AND lm.Status ='Approved'
Group by ls.Leave_Type
How would you convert the above sql query to linq? Thanks :)
Edit :
from p in db.PY_LeaveTransactionMasterTAB.AsEnumerable()
join e in db.PY_LeaveTransactionSubsidaryTAB.AsEnumerable() on p.LV_TransMasterId equals e.LV_TransMasterId into grp
where p.SystemCode == SysCode && p.EmployeeCode == EmpCode && p.Status == "Approved"
group grp by e.Leave_Type // This line is invalid Why?
The above is what I have tried so far, why can't I do e.Leave_Type or what is the right way to do group grp by e.Leave_Type?
You could try this:
(from p in db.PY_LeaveTransactionMasterTAB
join e in db.PY_LeaveTransactionSubsidaryTAB on p.LV_TransMasterId equals e.LV_TransMasterId
where p.SystemCode == SysCode && p.EmployeeCode == EmpCode && p.Status == "Approved"
group new {p,e} by new {e.Leave_Type } into gr
select new
{
Leave_Type = gr.Key.Leave_Type ,
Count = gr.Count()
}).ToList();

Left outter join linq

How do i change the training events into a left outer join in training events im very basic at linq so excuse my ignorance its not retrieve records that don't have any trainnevent reference attached to it
var q = from need in pamsEntities.EmployeeLearningNeeds
join Employee e in pamsEntities.Employees on need.EmployeeId equals e.emp_no
join tevent in pamsEntities.TrainingEvents on need.TrainingEventId equals tevent.RecordId
where need.EmployeeId == employeeId
where need.TargetDate >= startdate
where need.TargetDate <= enddate
orderby need.TargetDat
It's best to use where in combination with DefaultIfEmpty.
See here: LEFT JOIN in LINQ to entities?
var query2 = (
from users in Repo.T_Benutzer
from mappings in Repo.T_Benutzer_Benutzergruppen.Where(mapping => mapping.BEBG_BE == users.BE_ID).DefaultIfEmpty()
from groups in Repo.T_Benutzergruppen.Where(gruppe => gruppe.ID == mappings.BEBG_BG).DefaultIfEmpty()
//where users.BE_Name.Contains(keyword)
// //|| mappings.BEBG_BE.Equals(666)
//|| mappings.BEBG_BE == 666
//|| groups.Name.Contains(keyword)
select new
{
UserId = users.BE_ID
,UserName = users.BE_User
,UserGroupId = mappings.BEBG_BG
,GroupName = groups.Name
}
);
var xy = (query2).ToList();
Which is equivalent to this select statement:
SELECT
T_Benutzer.BE_User
,T_Benutzer_Benutzergruppen.BEBG_BE
-- etc.
FROM T_Benutzer
LEFT JOIN T_Benutzer_Benutzergruppen
ON T_Benutzer_Benutzergruppen.BEBG_BE = T_Benutzer.BE_ID
LEFT JOIN T_Benutzergruppen
ON T_Benutzergruppen.ID = T_Benutzer_Benutzergruppen.BEBG_BG

How can I perform a left join and exclude results that match a subquery in LINQ?

Need to convert this sql query to LINQ
SELECT *
FROM
parcels p
LEFT JOIN leases l ON p.parcels_pk = l.parcels_fk
WHERE
l.parcels_fk IS NULL
AND p.parcels_pk NOT IN (SELECT parcels_fk FROM application_parcels)
ORDER BY parcel
tried this:
var qry = from p in db.Parcels
join l in db.Leases on p.Id equals l.pk_parcel
where l.pk_parcel == null
&& !(from ap in db.ApplicationParcels
select ap.ParcelId).Contains(p.Id)
orderby p.Name
// SELECT * FROM parcels
var result = from p in parcels
// LEFT JOIN leases ON p.parcels_pk = l.parcels_fk
join llj in leases on p.parcels_pk equals llj.parcels_fk into lj
from l in lj.DefaultIfEmpty()
// WHERE l.parcels_fk IS NULL
where l.parcels_fk == null
// AND p.parcels_pk NOT IN (...)
&& !application_parcels.Any(x => x.parcels_fk == p.parcels_pk)
// ORDER BY [p.]parcel
order by p.parcel
select new { parcel = p, lease = l };
Assuming i have your schema correct.
But in the future:
First supply what you've tried (show an effort).
Have a look at LINQPad, it's very helpful.

converting SQL join with group by and MAX to Linq

I have Created following query in sql but i am not able to find out how to implement StatusAndTrackingNotes table join in my linq:
SELECT *
FROM [Application] APP
join User USR on APP.ApplicationId = USR.UserApplicationId
join
(Select MAX(TrackingDate) as MaxDateTD,TrackingApplicationId
From StatusAndTrackingNotes
where TrackingLoanType = 1 and ((TrackingStatusCode <= 52 and TrackingStatusCode >= 50) or TrackingStatusCode = 62)
group by TrackingApplicationId) MTND on APP.ApplicationId = MTND.TrackingApplicationId
join Details DTL on APP.ApplicationId = DTL.ApplicationId
join ApplicationFees AF on APP.ApplicationId = AF.ApplicationId
where APP.LatestStatus = 'F' and DTL.Type = 1 and DTL.FundingDate >= '2011-06-01' and DTL.FundingDate <= '2013-06-30'
and AF.FirstRefPaidDate is not null
Kindly help me with the syntax.First i was using using simple query with joins and then
([Linq Query]).GroupBy(i => i.TrackingApplicationId).Select(g => g.OrderByDescending(c => c.TrackingDate).FirstOrDefault());
but it doesnt return any result. Kindly help.
Thanks in advance
I would solve it by creating StatusAndTrackingNotes as separate query and join and group it to the "main query". I.e:
var trackingQuery =
from t in statusAndTrackingNotes
where t.TrackingLoanType == 1 && (t.TrackingStatusCode <= 52 && t.TrackingStatusCode >=50) || t.TrackingStatusCode == 62
group t by t.TrackingApplicationId into trackings
select new
{
TrackingApplicationId = trackings.Key,
MaxDate = trackings.Max(t => t.TrackingDate)
};
var appQuery =
from app in Application
join t in trackingQuery on app.ApplicationId equals t.TrackingApplicationId
/* other joins here */
select new
{
app,
t.MaxDate,
};