This question already has answers here:
Left outer join in linq
(4 answers)
Closed 8 years ago.
I have a sql query which has innerjoin and leftouter join's which is very tricky to mr to convert to LINQ.
SELECT project.ID, project.No, project.Name,
APPLN.Id,APPLN.Name,SAR.Name
FROM Phasefact phase WITH (NOLOCK)
INNER JOIN AProject project WITH (NOLOCK) on phase.Id = project.ID
INNER JOIN Application APPLN WITH (NOLOCK) ON project.AppId = APPLN.Id
LEFT OUTER JOIN Master master WITH (NOLOCK) ON phase.amId = master.Id
INNER JOIN Ref SAR WITH (NOLOCK) ON SAR.ID = master.Ref_Id
WHERE phase.ID = 123
It is bit confusing as it contains "left outer join". Someone please help.
Maybe something like this:
var result=(
from phase in db.Phasefact
join project in db.AProject
on phase.Id equals project.ID
join APPLN in db.Application
on project.AppId equals APPLN.Id
//Left join
from master in db.Master
.Where(a=>a.Id==phase.amId).DefaultIfEmpty()
join SAR in db.Ref
on SAR.ID equals master.Ref_Id
where phase.ID == 123
select new
{
project.ID,
project.No,
project.Name,
APPLN.Id,
APPLN.Name,
SAR.Name
}
);
EDIT
But i don't get the left join. Why are you using a left join? To me it looks like you first use a left join:
LEFT OUTER JOIN Master master WITH (NOLOCK) ON phase.amId = master.Id
And the after that you have a join that limits the result like this:
INNER JOIN Ref SAR WITH (NOLOCK) ON SAR.ID = master.Ref_Id
This will be the same as doing this:
INNER JOIN Master master WITH (NOLOCK) ON phase.amId = master.Id
INNER JOIN Ref SAR WITH (NOLOCK) ON SAR.ID = master.Ref_Id
I am giving you an basic idea of left outer join in LINQ
var lines = from p in db.Phasefact
join m in db.Master on m.Id equals
p.amId into p_m
where p.ID == 123
from m in p_m.DefaultIfEmpty()
select new { p.ID };
Now you can convert this much more according to your logic... or Query.......
Related
I am not trying to join my table using left outer join in LINQ where one of my join conditions does not satisfy. How can I still get the default record in my dataset? My SQL query runs perfectly fine but my join query is not returning the data.
Below is my SQL query where my left outer join works fine:
select
w.issueid as Issue
from worklog w
join jiraissue as j on w.issueid=j.ID
join issuetype AS ty ON ty.ID = j.issuetype
join project AS p on p.ID=j.PROJECT
left outer join customfieldvalue cfv on cfv.ISSUE = w.issueid
Below is my LINQ query in C# where if cfv.issue in the last join is not available in the table, I want to still return the default column.
var data = (from w in worklogs
join i in issuetypes on j.issuetype equals i.ID
join p in projects on j.PROJECT equals p.ID into table0
from c in table0.DefaultIfEmpty()
join cfv in customfieldvalues on w.issueid equals cfv.ISSUE into table1
from d in table1.DefaultIfEmpty()
{
IssueKey = l.Key.pkey + '-' + l.Key.issuenum,
Hours = l.Sum(w => w.timeworked)
}).ToList();
Any help is appreciated.
Thank you.
I've been following a few examples from this website on how to create Linq Left Outer Join queries but I haven't found any examples of where the "outer key in the left join doesn't point to the inner key but instead points to a previous key". Bear with me for that phrasing I know it's not correct but have a look at the following snippets of code and maybe it will be clearer.
Specifically, see the first left join where sp.SalesPersonID = j.SalesPersonID.
select rt.Name as ResourceType, s.FirstName + ' ' + s.Surname as Supervisor, sp.FirstName + ' ' + sp.LastName as SalesPerson, tr.OrderCodeID, tr.SkillID
, j.CustomerName, j.JobNumber
from dbo.TaskResource tr join projects.Task t on t.ID = tr.taskiD
join dbo.ResourceType rt on rt.ID = tr.ResourceTypeID
join projects.projecttask pt on pt.taskid = tr.taskid
join projects.jobproject jp on jp.projectid = pt.projectid
join crm.tbljobs j on j.jobid = jp.jobid
left join common.tblSalesPersons sp on sp.SalesPersonID = j.SalesPersonID
left join common.tblSupervisors s on s.SupervisorID = j.SupervisorID
where JobDeleted is null or JobDeleted = 0
order by ResourceType
When converted to Linq it would make
...from j in temp1.DefaultIfEmpty()
join sp in dbc.tblSalesPersons on j.SalesPersonID equals sp.SalesPersonID into temp2
So far so good. But when I do the next left join I though it would just be the same thing but pointing to one of the previous keys as I mentioned earlier so instead of using the sp variable which I've seen several examples of, I use the j variable which is from a previous join:
from sp in temp2.DefaultIfEmpty()
join s in dbc.tblSupervisors on j.SupervisorID equals s.SupervisorID
Here is the full code snippet:
List<ResourceTreeObject> resourceTreeObjects = (
from tr in dbc.TaskResources
join t in dbc.Tasks on tr.TaskID equals t.ID
join rt in dbc.ResourceTypes on tr.ResourceTypeID equals rt.ID
join pt in dbc.ProjectTasks on tr.TaskID equals pt.TaskID
join jp in dbc.JobProjects on pt.ProjectID equals jp.ProjectID
join j in dbc.tblJobs on jp.JobID equals j.JobID into temp1
from j in temp1.DefaultIfEmpty()
join sp in dbc.tblSalesPersons on j.SalesPersonID equals sp.SalesPersonID into temp2
from sp in temp2.DefaultIfEmpty()
join s in dbc.tblSupervisors on j.SupervisorID equals s.SupervisorID
where j.JobDeleted == null || j.JobDeleted == 0
select new ResourceTreeObject
{
TaskResourceID = tr.ID
,
TaskID = tr.TaskID
,
ResourceTypeID = tr.ResourceTypeID
,
ResourceType = rt.Name
,
SkillID = tr.SkillID
,
OrderCodeID = tr.OrderCodeID
,
PermissionID = tr.PermissionID
,
JobID = j.JobID
,
JobNumber = j.JobNumber
,
CustomerName = j.CustomerName
,
Salesperson = sp.FirstName + " " + sp.LastName
,
Supervisor = s.FirstName + " " + s.Surname
}).ToList();
And this results in the wrong query. The last "left join" is treated like an inner join and returns the wrong number of rows. So in essence what I'm asking is, how do I (in LinQ) do two consecutive left outer joins after doing several consecutive inner joins but use the key from one of the previous tables in my left out join?
Also I'm not sure what the correct terminology for inner/outer keys etc. hence the awkward phrasing and title. Perhaps someone could correct that so it would be more beneficial to others. Thank you.
Your LINQ translation is just a little off.
The SQL has an inner join on crm.tbljobs followed by outer joins on common.tblSalesPerson and common.tblSupervisors.
The LINQ has outer joins on dbc.tblJobs and dbc.tblSalesPersons followed by an inner join on dbc.tblSupervisors.
into temp1 ... from j in in temp1.DefaultIfEmpty() makes the outer join happen on the table introduced prior to the into, which is dbc.tblJobs.
So it should be:
...
// inner join
join j in dbc.tblJobs on jp.JobID equals j.JobID
// left outer join
join sp in dbc.tblSalesPersons on j.SalesPersonID equals sp.SalesPersonID into salesPersons
from sp in salesPersons.DefaultIfEmpty()
// left outer join
join s in dbc.tblSupervisors on j.SupervisorID equals s.SupervisorID into supervisors
from s in supervisors.DefaultIfEmpty()
...
I changed temp1 and temp2 to more meaningful names to demonstrate what they represent in the outer join syntax. Note the relationship and relative position of dbc.tblSalesPersons to salesPersons, for example.
One more thing to remember is that sp and s can be null, so make sure you check for that before accessing their FirstName, LastName, and Surname properties.
I am converting an SQL query to LINQ. It has multiple inner, left and right joins. I'm checking the generated SQL from LINQ in every step. But the problem is based on the selection the generated sql query changes.
Below my Linq
var a = from freight in billingEntity.FreightCharges.AsNoTracking()
join service in billingEntity.ServiceTypes.AsNoTracking()
on freight.ServiceTypeId equals service.Id
join transport in billingEntity.TransportationTypes.AsNoTracking()
on freight.TransportationTypeId equals transport.Id
join division in billingEntity.DivisionDetails.AsNoTracking()
on freight.OriginId equals division.OriginID
join mail in billingEntity.Mailclasses.AsNoTracking()
on freight.MailClassId equals mail.MailClassId
into mailClassFreight
from mail in mailClassFreight.DefaultIfEmpty()
join process in billingEntity.ProcessingCategories.AsNoTracking()
on freight.ProcessingcategoryId equals process.ProcessingCategoryId
into processFreight
from processCategory in processFreight.DefaultIfEmpty()
select mail;
string v = a.ToString();
This generated SQL as
SELECT
[Extent3].[MailClassId] AS [MailClassId],
[Extent3].[MailClassName] AS [MailClassName],
[Extent3].[CreatedDate] AS [CreatedDate]
FROM [dbo].[FreightCharges] AS [Extent1]
INNER JOIN [dbo].[DivisionDetails] AS [Extent2] ON [Extent1].[OriginId] = [Extent2].[OriginID]
LEFT OUTER JOIN [dbo].[Mailclass] AS [Extent3] ON [Extent1].[MailClassId] = [Extent3].[MailClassId]
WHERE ([Extent1].[ServiceTypeId] IS NOT NULL) AND ([Extent1].[TransportationTypeId] IS NOT NULL)
Where I can see the dbo.ProcessingCategory is missing in the join.
If I do select processCategory the SQL generates with missing dbo.MailClass.
The SQL query I am trying to convert to LINQ is below
select * from
dbo.FreightCharges as fc
inner join dbo.ServiceType as st
on fc.ServiceTypeId = st.Id
inner join dbo.TransportationTypes as tt
on fc.TransportationTypeId = tt.Id
inner join dbo.DivisionDetails as dd
on fc.OriginId = dd.OriginId
left join dbo.Mailclass as mc
on fc.MailClassId = mc.MailClassId
left join dbo.ProcessingCategory as pc
on fc.ProcessingcategoryId = pc.ProcessingCategoryId
right join dbo.ContentTitle as ct
on fc.ContentTitleId = ct.ContentTitleId
inner join dbo.AccountDetails as ac
on ct.AccountId = ac.AccountId
where
fc.EffectiveThruDate >= '9999-12-31'
or
fc.EffectiveThruDate is null
You can change your query joins to left joins like this.
select * from
dbo.ContentTitle ct
inner join dbo.AccountDetails as ac
on ct.AccountId = ac.AccountId
left join dbo.FreightCharges as fc
on fc.ContentTitleId = ct.ContentTitleId and fc.EffectiveThruDate >= '9999-12-31'
left join dbo.ServiceType as st
on fc.ServiceTypeId = st.Id
left join dbo.TransportationTypes as tt
on fc.TransportationTypeId = tt.Id
left join dbo.DivisionDetails as dd
on fc.OriginId = dd.OriginId
left join dbo.Mailclass as mc
on fc.MailClassId = mc.MailClassId
left join dbo.ProcessingCategory as pc
on fc.ProcessingcategoryId = pc.ProcessingCategoryId
Linq equivalent
from ct in ContentTitles
join ac in AccountDetails on ct.AccountId equals ac.AccountId
join fc in FreightCharges on ct.ContentTitleId equals fc.ContentTitleId into lfc
from flfc in lfc.Where(f => f.EffectiveThruDate >= new DateTime(9999,12,31)).DefaultIfEmpty()
join st in ServiceTypes on flfc.ServiceTypeId equals st.Id into lst
from flst in lst.DefaultIfEmpty()
join tt in TransportationTypes on flfc.TransportationTypeId equals tt.Id into ltt
from fltt in ltt.DefaultIfEmpty()
join dd in DivisionDetails on flfc.OriginId equals dd.OriginId into ldd
from fldd in ldd.DefaultIfEmpty()
join mc in Mailclasses on flfc.MailClassId equals mc.MailClassId into lmc
from flmc in lst.DefaultIfEmpty()
join pc in ProcessingCategories on flfc.ProcessingcategoryId equals pc.ProcessingCategoryId into lpc
from flpc in lst.DefaultIfEmpty()
select new {ct, ac, lfc, lst ,ltt, ldd, lmc, lpc}
I have to query the database and to do so requires that I do quite a few inner joins and a couple of left outer joins. I've generated the SQL in a view but I am now having a bit of difficulty rewriting it to LINQ in my applications data layer.
FROM dbo.Organisation
INNER JOIN
dbo.EducationCourseVenue
INNER JOIN
dbo.EducationCourseVenueLocation ON dbo.EducationCourseVenue.Id = dbo.EducationCourseVenueLocation.EducationCourseVenueId ON
dbo.Organisation.GlobalEntityGUID = dbo.EducationCourseVenue.GlobalEntityGUID
INNER JOIN
dbo.CommunicationType
INNER JOIN
dbo.CommunicationTypeGlobalEntityMap ON dbo.CommunicationType.Id = dbo.CommunicationTypeGlobalEntityMap.CommunicationTypeId ON
dbo.EducationCourseVenue.GlobalEntityGUID = dbo.CommunicationTypeGlobalEntityMap.GlobalEntityGUID
INNER JOIN
dbo.Country
INNER JOIN
dbo.Address ON dbo.Country.Id = dbo.Address.CountryId
INNER JOIN
dbo.CountryRegion ON dbo.Country.RegionId = dbo.CountryRegion.Id ON
dbo.CommunicationTypeGlobalEntityMap.CommunicationTypeItemId = dbo.Address.Id
LEFT OUTER JOIN
dbo.AddressPostalDistrictMap
INNER JOIN
dbo.RegionItemDistrictMap ON dbo.AddressPostalDistrictMap.Id = dbo.RegionItemDistrictMap.Id
INNER JOIN
dbo.RegionTypeItem ON dbo.RegionItemDistrictMap.RegionTypeItemId = dbo.RegionTypeItem.Id ON
dbo.Address.Id = dbo.AddressPostalDistrictMap.AddressId
LEFT OUTER JOIN
dbo.RHSGarden
INNER JOIN
dbo.AddressGeographics ON dbo.RHSGarden.Id = dbo.AddressGeographics.NearestRHSGardenId ON dbo.Address.Id = dbo.AddressGeographics.AddressId
WHERE (dbo.CommunicationType.Code = 'AD')
This particular line of SQL is a problem for in LINQ
FROM dbo.Organisation
INNER JOIN
dbo.EducationCourseVenue
INNER JOIN
dbo.EducationCourseVenueLocation ON dbo.EducationCourseVenue.Id = dbo.EducationCourseVenueLocation.EducationCourseVenueId ON
dbo.Organisation.GlobalEntityGUID = dbo.EducationCourseVenue.GlobalEntityGUID
I don't know how to do a join in LINQ without specifying key joins and then doing another join below that.
Any ideas?
var q = from o in context.Organisation
join v in context.EducationCourseVenue on o.GlobalEntityGUID equals v.GlobalEntityGUID
join l in context.EducationCourseVenueLocation on v.Id equals l.EducationCouseVenueId
Is how i think of it, since your:
FROM dbo.Organisation
INNER JOIN
dbo.EducationCourseVenue
INNER JOIN
dbo.EducationCourseVenueLocation ON dbo.EducationCourseVenue.Id = dbo.EducationCourseVenueLocation.EducationCourseVenueId ON
dbo.Organisation.GlobalEntityGUID = dbo.EducationCourseVenue.GlobalEntityGUID
Corresponds to:
FROM dbo.Organisation as o
INNER JOIN dbo.EducationCourseVenue as v ON o.GlobalEntityGUID = v.GlobalEntityGUID
INNER JOIN dbo.EducationCourseVenueLocation as l ON v.Id = l.EducationCourseVenueId
I have 2 inner joins (3 tables) but I don't know and I find it hard to implement my research about outer join in LINQ. How do I change the last inner join to outer join, such that column will still join even if the column (Role) is null?
Here's an existing SQL version of this which I want to convert to LINQ:
SELECT dbo.EmployeeAccess.id, dbo.EmployeeAccess.EmpNo, dbo.EmployeeAccess.RoleID, dbo.EmployeeAccess.Active, dbo.EmployeeAccessLevel.Role,
dbo.View_HCM.LNameByFName
FROM dbo.EmployeeAccess LEFT OUTER JOIN
dbo.EmployeeAccessLevel ON dbo.EmployeeAccess.RoleID = dbo.EmployeeAccessLevel.id INNER JOIN
dbo.View_HCM ON dbo.EmployeeAccess.EmpNo = dbo.View_HCM.EmpNo
LINQ I now have with 2 inner joins:
(from ea in context.EmployeeAccesses
join vh in context.View_HCM on (Int16)ea.EmpNo equals vh.EmpNo
join rl in context.EmployeeAccessLevels on ea.RoleID equals rl.id
select new EmployeeWithEmail{
EmpNum = ea.EmpNo ?? 0,
EmailAddress = vh.EmailAddress,
LNameByFname = vh.LNameByFName,
Active2 = ea.Active ?? false
}).ToList();
}
Linq's outer join syntax uses 2 parts. First an into then DefaultIfEmpty
In your case, an outer join might look like this:
(from ea in context.EmployeeAccesses
join vh in context.View_HCM on (Int16)ea.EmpNo equals vh.EmpNo
join rl in context.EmployeeAccessLevels on ea.RoleID equals rl.id into outer_join
from subjoin in outer_join.DefaultIfEmpty()
select new EmployeeWithEmail{
EmpNum = ea.EmpNo ?? 0,
EmailAddress = vh.EmailAddress,
LNameByFname = vh.LNameByFName,
Active2 = ea.Active ?? false
}).ToList();
There are many tutorials on how to create the outer join in LINQ.