LINQ left outer join NullReferenceException - linq

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

Related

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 { ... }

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();

Linq Left Join not working

I am trying to get this query into Linq
SELECT [ID], [Name], LastSync, Phase
FROM [Store]
LEFT JOIN (
SELECT GLog.[StoreId] AS [StoreId], LastSync, Phase
FROM [GGCSyncLog] AS GLog
INNER JOIN (
SELECT MAX(G1.[DateTime]) AS LastSync, G1.[StoreId]
FROM [GGCSyncLog] AS G1
GROUP BY G1.[StoreId]
) AS G2 ON (GLog.[StoreId] = G2.[StoreId]) AND (GLog.[DateTime] = G2.[LastSync])
) AS MostRecentLog ON Store.[ID] = MostRecentLog.[StoreId]
Its results are
ID Name LastSync Phase
1 Sarasota 2010-07-31 5
2 Wellington 2010-07-31 8
3 Tampa International 2013-03-12 8
5 Events NULL NULL
6 PO Holding Store NULL NULL
My Linq returns the correct results except I'm missing the two rows with the null LastSync & Phase. Any idea what's wrong?
from s in Stores
join gLog in
(from g1 in GGCSyncLogs.DefaultIfEmpty()
join g in
(from g in GGCSyncLogs
group g by g.StoreId into gM
select new {
StoreId = gM.Key, LastSync = gM.Max(gg=>gg.DateTime) })
on new {g1.StoreId, LastSync = g1.DateTime} equals new {g.StoreId, g.LastSync}
select new {g1.StoreId, g.LastSync, g1.Phase})
on s.ID equals gLog.StoreId
select new {s.ID, s.Name,
LastSync = (gLog != null ? (DateTime?)gLog.LastSync : null),
Phase = (gLog != null ? (int?)gLog.Phase : null) }
You should read about join clause and How to: Perform Left Outer Joins.
It's hard to get working solution without database here, but hope this will help you get back on track:
var g2 = from g1 in GGCSyncLogs
group g1 by g1.StoreId into gM;
var MostRecentLogs = from gLog in GGCSyncLogs
join g in g2 on new { gLog.StoreId, LastSync = gLog.DateTime} equals new { g.StoreId, g.LastSync }
select new { gLog.StoreId, LastSync = gLog.Date, Phase = gLog.Phase };
var results = from s in Stores
join gLog in MostRecentLogs on s.Id equals gLog.StoreId into gl
from l in gl.DefaultIfEmpty(new { LastSync = null, Phase = null })
select new {
s.Id,
s.Name,
l.LastSync,
l.Phase
};
I had to use an "into"
from s in Stores
join gRec in
(from g in GGCSyncLogs
join g2 in
(from g1 in GGCSyncLogs
group g1 by g1.StoreId into gM
select new {StoreId = gM.Key,LastSync = gM.Max(gg=>gg.DateTime)})
on new {g.StoreId, LastSync = g.DateTime} equals new {g2.StoreId, g2.LastSync}
select new {g.StoreId, g2.LastSync, g.Phase})
on s.ID equals gRec.StoreId into gRec2
from gRec3 in gRec2.DefaultIfEmpty()
select new {s.ID, s.Name,
LastSync = (gRec3 != null ? (DateTime?)gRec3.LastSync : null),
Phase = (gRec3 != null ? (int?)gRec3.Phase : null) }

Multiple conditions with Joins in 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 };

Resources