How can I convert this query from SQL to linq - linq

Can anyone help me converting this SQL query to linq:
select fi.CreatedOn, fi.Id
from Branch br
inner join Asset a on br.Id = a.BranchId
inner join Inspection i on i.AssetId = a.Id
inner join FormInstance fi on i.FormInstanceId = fi.Id
inner join [User] u on u.HomeBranchId = br.Id
where br.Id like 'xxx'
group by fi.CreatedOn, fi.Id
order by fi.CreatedOn desc
This is what I got so far, but I don't understand how to do the group by part
from fi in model.FormInstance
join ins in model.Inspections on fi.Id equals ins.FormInstanceId
join a in model.Assets on ins.AssetId equals a.Id
join br in model.Branches on a.BranchId equals br.Id
join usr in model.Users on br.Id equals usr.HomeBranchId
where br.Id == gBranchId
group fi by fi.Id

You have missed defining right grouping key.
query =
from fi in model.FormInstance
join ins in model.Inspections on fi.Id equals ins.FormInstanceId
join a in model.Assets on ins.AssetId equals a.Id
join br in model.Branches on a.BranchId equals br.Id
join usr in model.Users on br.Id equals usr.HomeBranchId
where br.Id == gBranchId
group fi by new { fi.CreatedOn, fi.Id } into g
select g.Key;
query = query.OrderByDescending(x => x.CreatedOn);

Related

Doing a Left outer join in a linq query

I have the query below that works in sqllite with a left outer join
select * from customer cu
inner join contract cnt on cu.customerId = cnt.customerid
inner join address addy on cu.addressid = addy.addressId
inner join csrAssoc cassc on cu.customerid = cassc.customerId
left outer join CustomerServiceRepresentative csrr on cassc.csrid = csrr.customerservicerepresentativeId
inner join customerServiceManager csmm on cassc.csmid = csmm.customerservicemanagerId
where cu.customernumber = '22222234'
I want to be able to apply a left outer join on this line in the linq query below
join csrr in objCsrCustServRep.AsEnumerable() on cassc.CsrId equals
csrr.CustomerServiceRepresentativeId
VisitRepData = (from cu in objCustomer.AsEnumerable()
join cnt in objContract.AsEnumerable() on cu.customerId equals cnt.customerId
join addy in objAddress.AsEnumerable() on cu.addressId equals addy.addressId
join cassc in objCsrAssoc.AsEnumerable() on cu.customerId equals cassc.CustomerId
join csrr in objCsrCustServRep.AsEnumerable() on cassc.CsrId equals
csrr.CustomerServiceRepresentativeId
join csmm in objCustServMan on cassc.CsmId.ToString() equals csmm.customerServiceManagerId
where cu.CustomerNumber == (customernbr)
How can I do a left outer join in a linq query?
Here is my comment after adjusting and running the code. The other section is also added. All am getting is object is not set to an instance of an object.
var VisitRepData = from cu in objCustomer.AsEnumerable()
join cnt in objContract.AsEnumerable() on cu.customerId equals cnt.customerId
join addy in objAddress.AsEnumerable() on cu.addressId equals addy.addressId
join cassc in objCsrAssoc.AsEnumerable() on cu.customerId equals cassc.CustomerId
join csrr in objCsrCustServRep.AsEnumerable() on cassc.CsrId equals
csrr.CustomerServiceRepresentativeId into temp
from tempItem in temp.DefaultIfEmpty()
join csmm in objCustServMan on cassc.CsmId.ToString() equals csmm.customerServiceManagerId
where cu.CustomerNumber == (customernbr)
select new
{
cu.customerId,
cu.CustomerNumber,
cu.customerName,
cu.dateActive,
cnt.contractExpirationDate,
addy.street,
addy.street2,
addy.city,
addy.state,
addy.zipcode,
cu.EMail,
cu.phoneNo,
cu.faxNumber,
csmm.customerServiceManagerName,
tempItem.CustomerServiceRepresentativeName,
};
foreach (var item in VisitRepData)
{
var one = item.customerId;
var two = item.CustomerNumber;
}
Per documentation:
A left outer join is a join in which each element of the first collection is returned, regardless of whether it has any correlated elements in the second collection. You can use LINQ to perform a left outer join by calling the DefaultIfEmpty method on the results of a group join
(emphasis mine)
Based on MSDN link above, and if I understood your requirements correctly, query should look like this:
VisitRepData = from cu in objCustomer.AsEnumerable()
join cnt in objContract.AsEnumerable() on cu.customerId equals cnt.customerId
join addy in objAddress.AsEnumerable() on cu.addressId equals addy.addressId
join cassc in objCsrAssoc.AsEnumerable() on cu.customerId equals cassc.CustomerId
join csrr in objCsrCustServRep.AsEnumerable() on cassc.CsrId equals
csrr.CustomerServiceRepresentativeId into temp
from tempItem in temp.DefaultIfEmpty()
join csmm in objCustServMan on cassc.CsmId.ToString() equals csmm.customerServiceManagerId
where cu.CustomerNumber == (customernbr)
Specifically, the left outer join is performed with this code:
join csrr in objCsrCustServRep.AsEnumerable()
on cassc.CsrId equals csrr.CustomerServiceRepresentativeId
into temp
from tempItem in temp.DefaultIfEmpty()

Linq left outer join and group by issue

Hi All my following query returns results like this:
lstView.DataSource = (from h in context.HolidayMains
join hd in context.HolidayDetails on h.Id equals hd.HolidayMainId into hd2
from hd in hd2.DefaultIfEmpty()
join e in context.Employees on h.CreatedBy equals e.Id into e2
from e in e2.DefaultIfEmpty()
join o in context.OfficeLocations on hd.OfficeLocation equals o.Id into o2
from o in o2.DefaultIfEmpty()
select new
{
h.HolidayTitle,
h.Date,
OfficeLocation = o.Name,
CreatedBy = e.Name,
h.Id
}).ToList();
But I need result like this :
How it can be done?

join on subquery results

I've got a table called IssueStatuses and another table called Issues. Issues has a StatusID and SubStatusID, both of which are from the IssueStatuses table which has an additional field that states if it's a SubStatus or not, like so:
IssueStatuses
IssueStatusID
IssueStatus
IsSubStatus
I'm trying to get a list of SubStatuses for a particular list of Issues. In SQL it's:
SELECT iss.IssueStatus, COUNT(iss.IssueStatus) AS Total
FROM Issues AS Issues
INNER JOIN Rooms r ON Issues.RoomID = r.RoomID
INNER JOIN Locations l ON l.LocationID = r.LocationID
INNER JOIN Customers c ON l.CustomerID = c.CustomerID
INNER JOIN (SELECT * FROM IssueStatuses WHERE IsSubStatus = 0) ist ON Issues.IssueStatusID = ist.IssueStatusID
INNER JOIN (SELECT * FROM IssueStatuses WHERE IsSubStatus = 1) iss ON Issues.IssueSubStatusID = iss.IssueStatusID
WHERE c.Customer = 'ABC'
AND l.Location = 'MySite'
GROUP BY iss.IssueStatus
but I"m having trouble converting it to LINQ. The desired output would be something like:
IssueStatus | Total
-------------------
Open 15
Delayed 25
On Time 8
Here's what I've tried with LINQ:
var query = from i in Issues
join r in Rooms on i.RoomID equals r.RoomID
join l in Locations on r.RoomID equals l.LocationID
join c in Customers on l.CustomerID equals c.CustomerID
where i.IssueStatusID == (from ist in IssueStatuses
where ist.IsSubStatus == false
select ist)
&& i.IssueSubStatusID == (from iss in IssueStatuses
where iss.IsSubStatus == true
select iss)
&& c.Custome == "ABC"
&& l.Location == "MySite"
group i by i.IssueStatus
but I know it's wrong because LINQPad throws an error stating:
can't convert int to type Models.IssueStatus
What I need to do is use iss.IssueStaus to group on but I can't access it. Can someone tell me what I'm doing wrong?
How about this (untested but I should be close):
var query = from i in Issues
join r in Rooms on i.RoomID equals r.RoomID
join l in Locations on r.LocationID equals l.LocationID
join c in Customers on l.CustomerID equals c.CustomerID
join ist in IssueStatuses on i.IssueStatusID equals ist.IssueStatusID
join iss in IssueStatuses on i.IssueSubStatusID equals iss.IssueStatusID
where !ist.IsSubStatus && iss.IsSubStatus
&& c.Customer == "ABC"
&& l.Location == "MySite"
group i by iss.IssueStatus into g
select new {IssueStatus = g.Key, Total = g.Count()}
Your two inner from statements return objects and not IDs ... select the ID you need like ist.IssueStatusID:
var query = from i in Issues
join r in Rooms on i.RoomID equals r.RoomID
join l in Locations on r.RoomID equals l.LocationID
join c in Customers on l.CustomerID equals c.CustomerID
where (from ist in IssueStatuses
where ist.IsSubStatus == false
select ist.IssueStatusID).Contains(i.IssusStatusID)
&& (from iss in IssueStatuses
where iss.IsSubStatus == true
select iss.IssueStatusID).Contains(i.IssueSubStatusID)
&& c.Customer == "ABC"
&& l.Location == "MySite"
group i by i.IssueStatus

LINQ to SQL: Two left outer join with multiple join conditions

Here's my SQL query:
Select <a bunch of columns>
from fields f
join Table1 c1 on c1.fieldID = f.ID and c1.year = 2014
join Table2 fRes on f.ID = fRes.fieldID
join Table3 stst on f.ID = stst.fieldID
join Table4 model on c1.ID = model.yearID
left join Table5 fA on f.ID = fA.fieldID and fA.year = 2014
left join Table6 nA on f.ID = nA.fieldID and nA.year = 2014
where fA.sourcename IS NULL and nA.Sourcename IS NULL
LINQ to SQL:
from f in BasicDataAccess.Data.FieldsList
join c1 in BasicDataAccess.Data.Table1List on f.ID equals c1.fieldID
join fRes in BasicDataAccess.Data.Table2List on f.ID equals fRes.fieldID
join soilTst in BasicDataAccess.Data.Table3List on f.ID equals soilTst.fieldID
join modelRsNM in BasicDataAccess.Data.Table4List on c1.ID equals modelRsNM.YearID
join fA in BasicDataAccess.Data.Table5List on f.ID equals fA.fieldID into group1
from g1 in group1.Where(fA => fA.Year == reportYear).DefaultIfEmpty()
join nA in BasicDataAccess.Data.Table6List on f.ID equals nA.fieldID into group2
from g2 in group2.Where(nA => nA.Year == reportYear).DefaultIfEmpty()
where g1.sourceName == null && g2.sourceName == null
Issue: the query when executed throws Nullreference exception was unhandled..Object reference not set to an instance of an object error..
What am I missing? Is it possible to reference the left outer join table in where clause? Please help!
As far as I can see, this line
from g1 in group1.Where(fA => fA.Year == reportYear).DefaultIfEmpty()
can produce null if there's no rows. In this case, when you try to filter it (where g1.sourceName == null) you'll get null reference (because g1 is null).

Convert SQL select statement to Linq

How can I convert the following SQL select statement to Linq?
SELECT u.Name FROM User u AS DDC
INNER JOIN Country c ON c.UserId = u.UserId
INNER JOIN (
SELECT AddressId,
Address,
PC,
FROM AddressTbl a
WHERE a.CountryId = 1
) AS Addresses ON Addresses.AddressId= u.AddressId
WHERE
u.UserIs = #UserId AND
Addresses.AddressId= #AddressId
Any good reading references?
from u in Users join
c in Country on c.UserId equals u.UserId
join a in Address on a.AddressId equals u.AddressId
where a.CountryId == 1
select u.Name
You can try this out
http://www.sqltolinq.com/

Resources