SQL Outer Join in LINQ - c#

I've got the following LINQ Query
from s in db.tblSave
join a in db.tblAssessment on s.AssessmentID equals a.Id
join staff in db.tblStaff on s.StaffID equals staff.Id
join student in db.tblStudent on s.StudentID equals student.Id
join signed in db.tblSaveSigned on s.Id equals signed.SaveID
select new
{
SaveID = s.Id,
StaffName = staff.StaffName,
AssessmentName = a.AssessmentName,
StudentName= student.StudentName,
CreatedDate = s.CreatedDate,
SignedDate = signed.SignedDate}
tblSaveSigned may not have a record against tblSave which is excluding some tblSave records. How do I include all tblSave records in my results? It's an outer join in SQL but not sure how to do it in LINQ.
Thanks in advance.
Is there an SQL to LINQ tool?

Below is the correct LINQ Query for put FULL OUTER JOIN on tblSave for tblSaveSigned. Thanks for NetMage for pointing me in the right direction.
from s in db.tblSave
join a in db.tblAssessment on s.AssessmentID equals a.Id
join staff in db.tblStaff on s.StaffID equals staff.Id
join student in db.tblStudent on s.StudentID equals student.Id
join signed in db.tblSaveSigned on s.Id equals signed.SaveID into signedj
from signed in signedj.DefaultIfEmpty()
select new
{
SaveID = s.Id,
StaffName = staff.StaffName,
AssessmentName = a.AssessmentName,
StudentName= student.StudentName,
CreatedDate = s.CreatedDate,
SignedDate = signed.SignedDate}

Related

The query has been canceled because the estimated cost of this query (27195) exceeds the configured threshold of 3000 in SQL Server 2014

I am using LINQ query to get rows with joining multiple tables and also used let keyword to get the list of rows for displaying multiple values in a display column. What's wrong with this linq query?
ImageLink
(from app in _dbContext.Appointments
join patient in _dbContext.Patients on app.PatientID equals patient.ID
join doc in _dbContext.Doctors on app.DoctorID equals doc.ID
join avail in _dbContext.DoctorsAvailabilities on app.AvailabilityID equals avail.ID
join loc in _dbContext.OfficeLocations on app.LocationID equals loc.ID
join state in _dbContext.CategoryDetails on loc.USState equals state.ItemID into StateGroup
from state in StateGroup.DefaultIfEmpty()
join appoint in _dbContext.CategoryDetails on app.Status equals appoint.ItemID into AppointmentStatusGroup
from appoint in AppointmentStatusGroup.DefaultIfEmpty()
let reasonVisit = (from v in _dbContext.DoctorAppointmentVisitReasons
join c in _dbContext.CategoryDetails on v.ReasonID equals c.ItemID
where c.CategoryID == CatergoryConstant.ReasonofVisit && v.AppointmentID == app.ID
select c.MasterData).ToList()
join appointmentSource in _dbContext.CategoryDetails on app.AppointmentSource equals appointmentSource.ItemID into AppointmentSourceGroup
from appointmentSource in AppointmentSourceGroup.DefaultIfEmpty()
let getReport = (from st in _dbContext.DoctorReportStatus
join cat in _dbContext.CategoryDetails on st.ReportStatus equals cat.ItemID
where st.StatusID == StatusConstant.Active && st.AppointmentID == app.ID
select new DoctorReportStatusViewModel() { ReportStatusText = cat.MasterData, ReportStatus = st.ReportStatus, AppointmentID = st.AppointmentID }).ToList()
let specility = (from s in _dbContext.DoctorSpecialities
join c in _dbContext.CategoryDetails on s.SpecialitiesID equals c.ItemID
where c.CategoryID == CatergoryConstant.DoctorSpeciality && s.DoctorID == doc.ID
select c.MasterData).ToList()

Linq query with 3 tables

Can you please let me know how to write a LINQ from for the following SQL query,
Select cr.Id
from [dbo].[User] usr, [dbo].[LikesStaging] lk, [dbo].[ChangeRequestStaging] cr
where usr.CustomerId=lk.[LikedBy] and usr.[Id] = 'user' and lk.[ChangeRequestId] = cr.[Id]
Was trying with the following query, but was not able to add usr.[Id] = 'user' condition in my linq query.
var result = from usr in lstUser
join lk in lstLikeStaging
on usr.CustomerId equals lk.LikedBy
join cr in lstChangeRequests
on lk.ChangeRequestId equals cr.Id
select new
{
cr.Id
};
Please let me know how to add this condition here.
var result = from usr in lstUser
join lk in lstLikeStaging on usr.CustomerId equals lk.LikedBy
join cr in lstChangeRequests on lk.ChangeRequestId equals cr.Id
where usr.id=="user"
select new
{
cr.Id
};
var result = from usr in lstUser
where usr.Id == "user"
join lk in lstLikeStaging
on usr.CustomerId equals lk.LikedBy
join cr in lstChangeRequests
on lk.ChangeRequestId equals cr.Id
select new
{
cr.Id
};

How can I rewrite the following SQL query into LINQ query?

I want to rewrite the following SQL query in LINQ. But my problem is that I don't know how to write an AND (&&) operator with a LINQ LEFT JOIN (look at my second left join).
SELECT emp.EmployeeId,
dsg.Name,
pob.CompanyContribution,
pob.EmployeeContribution,
pob.OpeningIncome
FROM HrmEmployees AS emp
LEFT JOIN HrmDesignations AS dsg ON emp.HrmDesignationId=dsg.Id
LEFT JOIN PfmOpeningBalance AS pob ON emp.Id=pob.HrmEmployeeId AND pob.CmnCalendarYearId=2
WHERE emp.Id=6
I tried the following one. But getting compile error-
from emp in dbContext.EmployeeList
join dsg in dbContext.hrmDesig on emp.HrmDesignationId equals dsg.Id into DSGLeftJoin
from dsglj in DSGLeftJoin.DefaultIfEmpty()
join pob in dbContext.PfOpeningBalances on emp.Id equals pob.HrmEmployeeId into POBLeftJoin
from poblj in POBLeftJoin.DefaultIfEmpty() && poblj.CmnCalendarYearId == clndrId
where emp.Id==empId
select new
{
empIdr = emp.Id,
EmployeeId = emp.EmployeeId,
EmployeeName = emp.Name,
Designation = dsglj.Name,
OpeningIncome = poblj.OpeningIncome,
EmployeeContribution = poblj.EmployeeContribution,
CompanyContribution = poblj.CompanyContribution
}
Try this.
(from emp in HrmEmployees
join dsg in HrmDesignations
on emp.HrmDesignationId equals dsg.Id
join pob in PfmOpeningBalance
on emp.Id equals pob.HrmEmployeeId AND pob.CmnCalendarYearId equals 2
into eGroup
from emps in eGroup.DefaultIfEmpty()
emp.Id=6
select new
{
EmployeeId =emp.EmployeeId,
Name=dsg.Name,
CompanyContribution=pob.CompanyContribution,
EmployeeContribution=pob.EmployeeContribution,
OpeningIncome=pob.OpeningIncome
}).ToList();
OK you can try like this;
from emp in dbContext.EmployeeList
join dsg in dbContext.hrmDesig on emp.HrmDesignationId=dsg.Id
join pob in dbContext.PfOpeningBalanceson new {emp.Id, jp=pob.CmnCalendarYearId} equals new {pob.HrmEmployeeId, jp=2}
where emp.Id=6
select new {emp.EmployeeId,
dsg.Name,
pob.CompanyContribution,
pob.EmployeeContribution,
pob.OpeningIncome};
Or like this;
from emp in dbContext.EmployeeList.Where(e=>e.Id.Equals(6))
join dsg in dbContext.hrmDesig on emp.HrmDesignationId=dsg.Id
join pob in dbContext.PfOpeningBalanceson.Where(x=>x.CmnCalendarYearId.Equals(2)) on emp.Id equals pob.HrmEmployeeId
select new {emp.EmployeeId,
dsg.Name,
pob.CompanyContribution,
pob.EmployeeContribution,
pob.OpeningIncome};

LINQ join queries on multiple table

I have struggling to run linq left on multiple tables.
tableA
Select all the (courseID, code, title) from courseInstances table
tableB
select (studyLevel_ID) from Courses table where courseID from tableA = CourseID from tableB. tableB has courseID
tableC
Select (StudyLevelDescription) from StudyLevel table where studyLevelID from tableB = studyLevel from tableC.
I believe I need left join on table A as I need all the records
I have done separate linq which are working fine but struggling to bring combine result
CourseInstances results
var processedCourseInstance =
(from _courseInstances in _uof.CourseInstances_Repository.GetAll()
join _courses in _uof.Courses_Repository.GetAll() on _courseInstances.CourseID equals _courses.CourseID
into a from b in a.DefaultIfEmpty()
orderby _courseInstances.CourseCode
select _courseInstances).ToList();
StudyLevel results for each course
var _CoursesStudyLevel_Lookup =
(from _course in _uof.Courses_Repository.GetAll()
join _studyLevel in _uof.StudyLevel_Repository.GetAll() on _course.StudyLevelId equals _studyLevel.StudyLevelID
select new {_course.CourseID, _course.StudyLevelId, _studyLevel.LevelDescription }).ToList();
I have managed to combine two results but NOT with LEFT join on CourseInstance table. This time I used LINQPad
from _courseInstances in CourseInstances
join _courses in Courses on _courseInstances.CourseID equals _courses.CourseID
join _studylevel in StudyLevels on _courses.StudyLevelId equals _studylevel.StudyLevelID
orderby _courseInstances.CourseCode
select new {_courseInstances.CourseID, _courseInstances.CourseCode, _courseInstances.CourseTitle, _courseInstances.UCASCode, _courses.StudyLevelId, _studylevel.LevelDescription, _studylevel.SLevelType }
for above SQL version as following;
SELECT [t0].[CourseID], [t0].[CourseCode], [t0].[CourseTitle],
[t0].[UCASCode], [t1].[StudyLevelId], [t2].[LevelDescription], [t2].[SLevelType]
FROM [CourseInstances] AS [t0]
INNER JOIN [Courses] AS [t1] ON [t0].[CourseID] = ([t1].[CourseID])
INNER JOIN [StudyLevel] AS [t2] ON [t1].[StudyLevelId] = ([t2].[StudyLevelID])
ORDER BY [t0].[CourseCode]
If i understand correctly, you want something like this?
from _courseInstances in CourseInstances
join c in Courses on _courseInstances.CourseID equals c.CourseID into courses
from _courses in courses.DefaultIfEmpty()
join sl in StudyLevels on _courses.StudyLevelId equals sl.StudyLevelID into studyLevels
from _studylevel in studyLevels.DefaultIfEmtpy()
orderby _courseInstances.CourseCode
select new {
_courseInstances.CourseID,
_courseInstances.CourseCode,
_courseInstances.CourseTitle,
_courseInstances.UCASCode,
_courses.StudyLevelId,
_studylevel.LevelDescription,
_studylevel.SLevelType
}
}
You can create a LINQ left join query with the into keyword and .DefaultIfEmpt().

how to use left join in entity framework query? [duplicate]

This question already has answers here:
LINQ - Left Join, Group By, and Count
(5 answers)
Closed 9 years ago.
I am working with entity framework 4.5. I have to convert an SQL query to entity query:
SELECT Customer.CustCode, Invoice.InvoiceId, Invoice.BatchNumber, Invoice.InvoiceDate, Invoice.AdjustFlag, Invoice.InvoiceAmount,
Invoice.InvoiceNote, Invoice.AmountPaid, Customer.BillingContact, Customer.BillingCompany, Customer.BillingStreet1,
Customer.BillingStreet2, Customer.BillingCity, Customer.BillingState, Customer.BillingZip, [Order].PickupDate, [Order].OrderNumber,
[Order].OrderTotal, [Order].ProNumber, [Order].PickupCompany, [Order].PickupCity, [Order].PickUpState, [Order].Dcompany,
[Order].Dcity, [Order].Dstate, CONVERT(varchar(5), DeliverInTime, 114) AS DelInTime, [Order].PiecesWeight1, [Order].BaseRATE,
[Order].POD, [Order].Requester, [Order].Po1, [Order].Po2, AccessorialCharge.Description,
OrderDriverExtraCharge.AccessorialChargeDesc, OrderDriverExtraCharge.AccessorialChargeAmount, [Order].NormalDiscount,
- 1 * [Order].DISCAmount AS DISCAmount
FROM (((Invoice INNER JOIN
[Order] ON Invoice.InvoiceId = [Order].InvoiceId) INNER JOIN
Customer ON Invoice.CustID = Customer.CustID) LEFT JOIN
OrderDriverExtraCharge ON [Order].OrderNumberId = OrderDriverExtraCharge.OrderNumberId) LEFT JOIN
AccessorialCharge ON OrderDriverExtraCharge.AccessorialChargeId = AccessorialCharge.AccessorialChargeId
where Invoice.InvoiceId = '1117782'
If I change OrderDriverExtraCharge.OrderNumberId) LEFT JOIN to OrderDriverExtraCharge.OrderNumberId) JOIN (simple join) or inner join it's not showing the right result.
I have tried this:
from I in db.Invoices
join O in db.Orders on I.InvoiceId equals O.InvoiceId
join C in db.Customers on I.CustId equals C.CustId
join OD in db.OrderDriverExtraCharges on O.OrderNumberId equals OD.OrderNumberId
join AC in db.AccessorialCharges on OD.AccessorialChargeId equals AC.AccessorialChargeId
where I.InvoiceId == invoice.InvoiceId
select new PrintInvoiceViewModel()
But it is not showing the required results. Please help me, I will mark your answer if it worked for me. Thank you.
You can do this:
from I in db.Invoices
join O in db.Orders on I.InvoiceId equals O.InvoiceId
join C in db.Customers on I.CustId equals C.CustId
from OD in db.OrderDriverExtraCharges
.Where(w=>w.OrderNumberId==O.OrderNumberId).DefaultIfEmpty()
from AC in db.AccessorialCharges
.Where(w=>w.AccessorialChargeId==OD.AccessorialChargeId).DefaultIfEmpty()
where I.InvoiceId == invoice.InvoiceId
select new PrintInvoiceViewModel()
Your should use DefaultIfEmpty method, which returns the elements of an IEnumerable<T>, or a default valued singleton collection if the sequence is empty:
from I in db.Invoices
join O in db.Orders on I.InvoiceId equals O.InvoiceId
join C in db.Customers on I.CustId equals C.CustId
join OD in db.OrderDriverExtraCharges on O.OrderNumberId equals OD.OrderNumberId into ODs
from OD in ODs.DefaultIfEmpty()
join AC in db.AccessorialCharges on OD.AccessorialChargeId equals AC.AccessorialChargeId into ACs
from AS in ACs.DefaultIfEmpty()
where I.InvoiceId == invoice.InvoiceId
select new PrintInvoiceViewModel()

Categories

Resources