Linq query join has error - linq

I'm attempting to filter cases where I only want cases that have case_manager EmployeeId's that are in criteria.EmployeeId which is IEnumerable.
This SQL statement is an example of the joins
SELECT c.Id, c.filenumber, c.title, cm.[Role], e.fname, e.lname
FROM [CASE] c
INNER JOIN CASE_MANAGER cm ON c.Id = cm.CaseId
INNER JOIN tblEmployees e ON cm.EmployeeId = e.Id
WHERE e.Id IN (154, 311)
My filter:
if (criteria.EmployeeIds != null)
cases = cases.Where(c => c.CASE_MANAGER.Any(cm => cm.tblEmployee.id == criteria.EmployeeIds));
I'm getting this error:
operator '==' cannot be applied to operands of type 'int' and 'IEnumerable<int>'
on this part of the filter:
cm.tblEmployee.id == criteria.EmployeeIds
How do I get this join correct with linq?

Related

Convert SQL to LINQ with multiple types of joins

I need to convert a SQL query into LINQ, either to Query Syntax or Method Syntax.
SELECT
IA.ItemId,
IVT.ItemName,
C.DeliveryMethod,
SUM(OD.Quantity) AS Qty
FROM OrderHeader OH
INNER JOIN OrderDetail OD ON OH.OrderId = OD.OrderId
LEFT JOIN Customer C ON OH.CustomerId = C.Id
LEFT JOIN ItemAvailability IA ON OD.ItemId = IA.RecId
INNER JOIN Inventory IVT ON IA.ItemId = IVT.ItemId
WHERE OH.DeliveryDate = '02/03/2023'
AND OH.OrderType = 'Web'
GROUP BY IA.ItemId, Ivt.ItemName, C.DlvMode
ORDER BY IA.ItemId
I've spent a long time Googling and YouTubing, but everyone provides examples of either just Inner Joins, Group Joins, or Left Joins. No one gave example of having both Inner Joins and Left Joins in the same query.
I know the syntax for a simple inner join like this:
SQL
SELECT OH.OrderId, OD.ItemId, OD.Quantity
FROM OrderHeader OH
INNER JOIN OrderDetail OD ON OH.OrderId = OD.OrderId
ORDER BY OD.ItemId
LINQ
from oh in OrderHeader
join od in OrderDetail on oh.OrderId equals od.OrderId
orderby ordt.IItemId
select new {
OrderId = oh.OrderId,
ItemId = od.ItemId,
Quantity = od.Quantity
}
And I know the LINQ syntax for left join also. But I am having trouble to figure out how to have both inner and left joins in one LINQ query.
I hope someone here can help, please.
Just combine join techniques together
var deliveryDate = ...;
var query =
from oh in OrderHeader
join od in OrderDetail on oh.OrderId equals od.OrderId
join c in Customer ON oh.CustomerId equals c.Id into cj
from c in cj.DefaultIfEmpty()
join ia in ItemAvailability on od.ItemId equals ia.RecId into iaj
from ia in iaj.DefaultIfEmpty()
join ivt in Inventory on ia.ItemId equals ivt.ItemId
where oh.DeliveryDate == deliveryDate && oh.OrderType == "Web"
group od by new { ia.ItemId, ivt.ItemName, c.DlvMode, c.DeliveryMethod } into g
select new
{
g.Key.ItemId,
g.Key.DeliveryMethod,
Qty = g.Sum(x => x.Quantity)
} into s
orderby s.ItemId
select s;

Inner Join with two equalities inside on clause in LINQ Lambda

I'm trying to convert a Sql query to a Linq Lambda style query. Thought this would be something easy but it turned out not.
SQL Query is as follows;
select distinct t1.ID from table1 t1
inner Join table2 t2on (t2.FromId= t1.Id or t2.ToId= t1.Id)
where t1.TenantId = 12
and t2.wId= 51
All examples I came across are for one clause joins so far. I wrote something like this
actStaList = _db.t1
.Join(_db.t2,
s => s.ID,
wf => wf.ToId,
(s, wf) => new { t1= s, t2= wf }
)
.Where(a => a.t1.Tenant.Guid == _tenantGuid)
.Select (m=>m.t1.ID)
.ToList();
It is obvious this won't work as the sql query above but still it's a start.
Still I can't figure where should I add the second part inside INNER JOIN and Distinct keyword.
One option you have is to use two separate Linq Queries and concat the result(and eliminating duplicates).
var left = t1.Join(t2,
s => s.ID,
wf => wf.ToId,
(s, wf) => new { t1= s, t2= wf }
).Select(x=>x);
var right = t1.Join(t2,
s => s.ID,
wf => wf.FromId,
(s, wf) => new { t1= s, t2= wf }
).Select(x=>x);
var actStaList = left.Concat(right).Select(m=>m.t1.ID)
.Distinct();
Please note I have omitted the Where Clause in the example as in the OP, both Sql version and your attempted Linq version seem to have different conditions. You can add them yourself.
The LINQ Join statement only supports equi-joins. For other types of equality you can't use the Join statement and have to code the equality manually. This is much easier in query syntax:
actStaList = (
from t1 in _db.table1
from t2 in _db.table2
where t2.FromId == t1.Id || t2.ToId == t1.Id
where t1.TenantId == 12 && t2.wId == 51
select t1.ID
).Distinct();
For the record, you can avoid the Distinct statement by executing this as a SQL EXISTS statement:
actStaList =
from t1 in _db.table1
where t1.TenantId == 12
where (from t2 in _db.table2
where t2.wId == 51 && (t2.FromId == t1.Id || t2.ToId == t1.Id)
select t2).Any()
select t1.ID;

Need help converting SQL into LINQ

SELECT ra.ResidentID, ra.RoomID, r.Number, ra.StartDate, p.FacilityID
FROM(
SELECT ResidentID, MAX(StartDate) AS max_start
FROM RoomAssignments
GROUP BY ResidentID
) m
INNER JOIN RoomAssignments ra
ON ra.ResidentID = m.ResidentID
AND ra.StartDate = m.max_start
INNER JOIN Rooms r
ON r.ID = ra.RoomID
INNER JOIN Person p
ON p.ID = ra.ResidentID
inner join ComplianceStage cs
ON cs.Id = p.ComplianceStageID
ORDER BY ra.EndDate DESC
I'm trying to figure out how to convert this to C# using LINQ. I'm brand new with C# and LINQ and can't get my subquery to fire correctly. Any chance one of you wizards can turn the lights on for me?
Update-----------------
I think I've got the jist of it, but am having trouble querying for the max startdate:
var maxQuery =
from mra in RoomAssignments
group mra by mra.ResidentID
select new { mra.ResidentID, mra.StartDate.Max() };
from ra in RoomAssignments
join r in Rooms on ra.RoomID equals r.ID
join p in Persons on ra.ResidentID equals p.ID
where ra.ResidentID == maxQuery.ResidentID
where ra.StartDate == maxQuery.StartDate
orderby ra.ResidentID, ra.StartDate descending
select new {ra.ResidentID, ra.RoomID, r.Number, ra.StartDate, p.FacilityID}
Following my LINQ to SQL Recipe, the conversion is pretty straight forward if you just follow the SQL. The only tricky part is joining the range variable from the subquery for max start date to a new anonymous object from RoomAssignments that matches the field names.
var maxQuery = from mra in RoomAssignments
group mra by mra.ResidentID into mrag
select new { ResidentID = mrag.Key, MaxStart = mrag.Max(mra => mra.StartDate) };
var ans = from m in maxQuery
join ra in RoomAssignments on m equals new { ra.ResidentID, MaxStart = ra.StartDate }
join r in Rooms on ra.RoomID equals r.ID
join p in Persons on ra.ResidentID equals p.ID
join cs in ComplianceStage on p.ComplianceStageID equals cs.Id
orderby ra.EndDate descending
select new {
ra.ResidentID,
ra.RoomID,
r.Number,
ra.StartDate,
p.FacilityID
};

Invalid Expression term Where

I have following LINQ statement:
from o in Orders
join od in OrderDetails on o.OrderNumber equals od.OrderNumber
join r in RMAs on o.OrderNumber equals r.OrderNumber
join rd in RMADetails on r.RMAnumber equals rd.RMAnumber
from i in Inventory
where( a => ( od.SKU == a.LocalSKU)).DefaultIfEmpty()//error is here
where (r.Status != "Pending" && od.Adjustment == false)
select new
{
r.Status,
o.Name,
o.Company,
o.Address,
o.Address2,
o.City,
o.State,
o.Country,
o.Email,
o.Zip,
o.Phone,
o.ShipName,
o.ShipCompany,
o.ShipAddress,
o.ShipAddress2,
o.ShipCity,
o.ShipCountry,
o.ShipState,
o.ShipPhone,
o.ShipZip,
o.OrderNumber,
o.ShippingTotal,
OrderDate = o.OrderDate,
SerialNumbers = rd.SerialNumbers ?? "",
o.SourceOrderID
}
It's giving Invalid Where term. What I want to use LEFT OUTER JOIN having SQL Equivalent left join Inventory i on od.SKU = i.LocalSKU
Try this:
var qry = from o in Orders
join od in OrderDetails.Where(od=>od.Adjustment == false) on o.OrderNumber equals od.OrderNumber
join i in Inventory on i.LocalSKU equals od.SKU into grp
from g in grp.DefaultIfEmpty()
join r in RMAs.Where(r=>r != 'Pending') on o.OrderNumber equals r.OrderNumber
join rd in RMADetails on r.RMAnumber equals rd.RMAnumber
select new
{
//set of columns here
};

Join statement in Linq to Sql

I need to write Join statment after writing query in linq
example :
var Query = (from Tab in Db.Employees
select Tab)
as i have some cases to perform join operation so
i need to do it on this Query Query.Join(Join with another Table like Department); I need the Syntax
if (DeptID != -1){ Query.Join(Join with table Department where FkDeptID = DeptID); }
Consider the usage of join in the LINQ 'query syntax':
from t1 in db.Table1
join t2 in db.Table2 on t1.field equals t2.field
select new { t1.field2, t2.field3}
Something like this?
var results = (from q in Query
join m in myList on q.SomeID = m.SomeID
select unknown);
Try using this query:
var Query =
from e in Db.Employees
join d in Db.Departments on e.FkDeptID equals d.DeptID into departments
select new
{
Employee = e,
Department = departments.SingleOrDefault(),
};
This works assuming that when e.FkDeptID == -1 that there is no record in the Departments table and in that case Department would be assigned null.
You should never have more than one department for an employee so I've used SingleOrDefault rather than FirstOrDefault.

Resources