I am working on creating a C# LINQ statement from a SQL query with multiple joins and aliases. I am having some trouble constructing the LINQ.
The SQL:
SELECT
store.Name as 'Store',
store.CreatedOn as 'StoreCreated',
supplier.Name as 'Supplier',
supplier.CreatedOn as 'SupplierCreated',
farm.Name as 'Farm',
farm.CreatedOn as 'FarmCreated',
FROM Users store
INNER JOIN UserRelationship toSupplier on store.ID = toSupplier.YId
INNER JOIN Users supplier ON supplier.ID = toSupplier.XId
INNER JOIN UserRelationship toFarm ON store.ID = toFarm.XId
INNER JOIN Users farm ON farm.ID = toFarm.YId
WHERE
store.Active= '1'
AND
supplier.Active = '1'
AND
farm.Active = '1'
This returns rows showing the relationships between the three parties and the dates.
So, far, I've got the following LINQ:
var newUserList = from store in Users
join toSupplier in UserRelationship on store.ID = toSupplier.YId
join supplier in Users on supplier.ID = toSupplier.XId
join toFarm in UserRelationship on store.ID = toFarm.XId
join farm in Users on farm.ID = toFarm.YId
Am I on the right track? Any help would be appreciated.
LINQ join syntax uses equals keyword instead of = in join condition:
var newUserList = from store in Users
join toSupplier in UserRelationship on store.ID equals toSupplier.YId
join supplier in Users on supplier.ID equals toSupplier.XId
join toFarm in UserRelationship on store.ID equals toFarm.XId
join farm in Users on farm.ID equals toFarm.YId
select ...
Related
I have prepared a SQL query and I'm having problem translating into LINQ query. Below I'm attaching my SQL query.
I have problems with inner join and left join that contains a select inside, and actually a second left join has another select inside a select as well, with group by.
This is really frustrating so maybe you could help me?
select * from Users u
inner join Pickups p on p.Number=u.Number
inner join Revisions r on r.Id=p.RevisionId and r.RevisionText='Done'
inner join (select u2.Id, count(u2.Id) clicks_num
from Users u2
inner join Clicks uc on uc.UserId=u2.Id
group by u2.Id) clicks on clicks.Id=u.Id
left join (select UserId, count(Id) scc
from (select distinct ucx.UserId, ucx.Id
from Clicks ucx
inner join Pickups ucpx on ucpx.Number=ucx.Number
inner join Revisions ucprx on ucprx.Id=ucpx.RevisionId and r.RevisionText='Done') t
group by UserId) s on s.UserId = u.Id
where clicks.clicks_num = s.scc;
I am starting with a simple one, but then could you give me an example how to make an inner select as join?
from u in Context.Set<Users>()
join p in Context.Set<Pickups>() on u.Number equals p.Number
join r in Context.Set<Revisions>() on p.RevisionId equals r.RevisionId
I'm trying to do the following query in linq-to-sql (joining 3 different tables):
select * from tbl_round r
inner join tbl_election e on r.fk_election_id = e.election_id
inner join tbl_meeting m on m.meeting_id = e.fk_meeting_id
Here is what I have so far but not correct:
from round in db.tbl_rounds
join meeting in db.tbl_meetings on election.fk_meeting_id equals meeting.meeting_id
join election in db.tbl_elections on round.fk_election_id equals election.election_id
select round;
The error I'm getting is that the name 'election' does not exist in the current context.
You will have to re-order the join statement probably like
from round in db.tbl_rounds
join election in db.tbl_elections on round.fk_election_id equals election.election_id
join meeting in db.tbl_meetings on election.fk_meeting_id equals meeting.meeting_id
select round;
Because you have "election" used before it is declared.
from round in db.tbl_rounds
join meeting in db.tbl_meetings on -->election<--.fk_meeting_id equals meeting.meeting_id
join -->election<-- in db.tbl_elections on round.fk_election_id equals election.election_id
select round;
In this case, you will need to change order in your query.
Query should look like this:
from round in db.tbl_rounds
join election in db.tbl_elections on round.fk_election_id equals election.election_id
join meeting in db.tbl_meetings on election.fk_meeting_id equals meeting.meeting_id
select round;
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().
I'm trying to convert this query (already working)
SELECT Building.NAME, COUNT([User].ID)
FROM BuildingUser
INNER JOIN Building ON Building.ID = BuildingUser.ID_BUILDING
INNER JOIN [User] ON [User].ID = BuildingUser.ID_USER
GROUP BY Building.NAME
To Linq to SQL, but I don't know what I'm doing wrong. Look at my trying
from buildinguser in db.GetTable<BuildingUser>()
join building in db.GetTable<Building>()
on buildinguser.ID_BUILDING equals building.ID
join user in db.GetTable<User>()
on buildinguser.ID_USER equals user.ID
group building by building.NAME into grpBuilding
select new
{
building = grpBuilding.Key,
users =
};
I just need to group my Buildings and count how many users each one has.
Simply use the the Count method:
from buildinguser in db.GetTable<BuildingUser>()
join building in db.GetTable<Building>()
on buildinguser.ID_BUILDING equals building.ID
join user in db.GetTable<User>()
on buildinguser.ID_USER equals user.ID
group building by building.NAME into grpBuilding
select new
{
building = grpBuilding.Key,
users = grpBuilding.Count()
};
My recent project I have a requirements to print receivable summary. I need to return entire rows from the OpeningBalance table and matching rows from VoucherHeader and Customers.
My SQL query is this
SELECT
OpeningBalance.OpenID, Sum(OpeningBalance.Amount) AS SumOfAmount,
Sum(VoucherHeader.Debit) AS SumOfDebit, Sum(VoucherHeader.Credit) AS SumOfCredit,
Customers.CustomerID, Customers.CustomerName
FROM
(OpeningBalance
LEFT OUTER JOIN
VoucherHeader ON OpeningBalance.OpenID = VoucherHeader.LedgerID)
INNER JOIN
Customers ON OpeningBalance.OpenID = Customers.CustomerID
WHERE
(((Customers.CustomerType)='Debtor')
AND ((VoucherHeader.VoucherDate)<#2013/06/02#))
GROUP BY
OpeningBalance.OpenID, Customers.CustomerID, Customers.CustomerName,
VoucherHeader.LedgerID
ORDER BY
Customers.CustomerName;
Please help.
SELECT OB.OpenID, Sum(OB.Amount) AS SumOfAmount,
Sum(VB.Debit) AS SumOfDebit, Sum(VB.Credit) AS SumOfCredit, CS.CustomerID,
CS.CustomerName FROM OpeningBalance OB
LEFT OUTER JOIN VoucherHeader VB ON OB.OpenID = VB.LedgerID
LEFT OUTER JOIN Customers CS ON OB.OpenID = CS.CustomerID
WHERE (((CS.CustomerType)='Debtor') AND ((VB.VoucherDate)<#2013/06/02#))
GROUP BY OB.OpenID, CS.CustomerID, CS.CustomerName, VB.LedgerID
ORDER BY CS.CustomerName;