Multiple conditions with Joins in Linq - linq

For the below code it gives the error
type reference failed in the call to Join
how can to fix this
var unp = from v in context.student.Include("subjects").Include("marks")
join n in context.AllStudents
on v.StudentDetails.student_Id equals n.Id
join ss in context.StudentHistory
on v.StBacklogs_Id equals ss.Id
join userName in context.Users
on v.CreatedBy_Id equals userName.Id
join externalId in context.Books
on new { ss.BookNumber, ss.Id } equals new { externalId.BookNumber, externalId.Id }
select new { v, n, ss, userName,externalId };

Related

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
};

Change to Left joins

How can I change this Linq query to left joins instead inner joins?
from EH in db.EventsHistory
join AH in db.EventsAttr on EH.TRANSACTIONID equals AH.TRANSACTIONID
join E in db.Events on EH.EVTID equals E.EVTID
group EH by new { EH.TRANSACTIONID, EH.MACGRP, EH.MACID, EH.ORDID, EH.ORDSPLIT, EH.LINID, EH.EVTDATETIME, EH.MATID, EH.PRODID, E.DESC, NUM_ATTR = AH.TRANSACTIONID } into grouped
select new { grouped.Key.TRANSACTIONID, grouped.Key.MACGRP, grouped.Key.MACID, grouped.Key.ORDID, grouped.Key.ORDSPLIT, grouped.Key.LINID, grouped.Key.EVTDATETIME, grouped.Key.MATID, grouped.Key.PRODID, grouped.Key.DESC, NUM_ATTR = grouped.Count() };
In Linq LEFT JOIN is created by using group join with method DefaultIfEmpty. The basic construction looks like this using query syntax:
var query = from c in db.Customers
join o in db.Orders on c.Id equals o.CustomerId into g
from o in g.DefaultIfEmpty()
select new
{
Customer = c,
Order = o
};
Example with method syntax:
var query = db.Customers
.GroupJoin(db.Orders, c => c.Id, o => o.CustomerId, (c, og) => new
{
Customer = c,
Order = og.DefaultIfEmpty()
});
So your query should look like this:
var query = from eh in db.EventsHistory
join ah in db.EventsAttr on eh.TransactionId equals ah.TransactionId into g
join e in db.Events on eh.EvtId equals e.EvtId into g2
from ah in g.DefaultIfEmpty()
from e in g2.DefaultIfEmpty()
group eh by new { ... } into grouped
select new { ... }

LINQ left outer join NullReferenceException

I am getting NullReferenceException when doing left outer join.
Similar query works in LINQ Pad but not in Visual Studio 2015. System.NullReferenceException was unhandled by user code
HResult=-2147467261
Message=Object reference not set to an instance of an object.
Thanks in advance.
.Net Core LINQ Code that does not work:
public IEnumerable<R> GetAll()
{
var results =
from a in uow.R.GetAll()
join b in uow.SSR.GetAll() on a.ID equals b.RID into g9
from c in g9.DefaultIfEmpty()
join d in uow.SS.GetAll() on c.SSID equals d.ID into g10
from e in g10.DefaultIfEmpty()
select new
{
a.Id,
SSID = c == null ? null : (int?)c.SSID,
e.Name
};
List<R> rList = new List<R>();
foreach (var a in results)
{
resourceList.Add(new R { ID = a.Id, SSID = a.SSID });
}
return rList.ToArray<R>();
}
`
var Result =
from a in Tbl_R
join b in Tbl_SS on a.ID equals b.RID into g9
from c in g9.DefaultIfEmpty()
join d in Lu_SS on c.SSID equals d.SSID into g10
from e in g10.DefaultIfEmpty()
select new
{
a.ID,
SSID = c == null ? null : (int?)c.SSID,
e.Name
};
Result.Dump();
SELECT t2.ID,
ISNULL(t17.SSID,'') as SSID
ISNULL(t17.Name,'') as Name
FROM R t2
LEFT JOIN SSR t16 ON t16.RID=t2.ID
LEFT JOIN SS t17 ON t16.SSID=t17.SSID

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
};

linq to entities left outer join

select SF.FOLDER_NAME,SF.CREATED_DATE,COUNT(st.FOLDER_ID)
from SURVEY_FOLDER SF with (nolock) left outer join SURVEY_TEMPLATE ST with (nolock)
on SF.FOLDER_ID=ST.FOLDER_ID
group by SF.FOLDER_NAME,SF.CREATED_DATE
I need this query in Linq :
I have tried this query,but unable to group by.
My Linq Query :
var data = (from xx in VDC.SURVEY_FOLDER
join yy in VDC.SURVEY_TEMPLATE
on xx.FOLDER_ID equals yy.FOLDER_ID into g
from grt in g.DefaultIfEmpty()
select
new
{
xx.FOLDER_NAME,
xx.CREATED_DATE,
count = g.Count()
}).ToList();
I got the Answer :
var data5 = (from SF in VDC.SURVEY_FOLDER
join ST in VDC.SURVEY_TEMPLATE on new { FOLDER_ID = SF.FOLDER_ID } equals new { FOLDER_ID = (Int64)ST.FOLDER_ID } into ST_join
from ST in ST_join.DefaultIfEmpty()
group new { SF, ST } by new
{
SF.FOLDER_NAME,
SF.CREATED_DATE
} into g
select new
{
g.Key.FOLDER_NAME,
CREATED_DATE = (DateTime?)g.Key.CREATED_DATE,
Column1 = (Int64?)g.Count(p => p.ST.FOLDER_ID != null)
}).ToList();

Resources