I'm struggling with a Linq query involving left joins. Here is the SQL I'm trying to convert:
SELECT EmailStats.EmailAddress, EmailVoting.DateAdded, EmailVoting.ResponseText,
EmailStats.DateSent, EmailAlerts.Name, UserDetails.EmployeeNumber
FROM EmailAlerts
INNER JOIN EmailStats
ON EmailAlerts.EmailAlertID = EmailStats.EmailAlertID
INNER JOIN UserDetails
ON EmailStats.UserId = UserDetails.UserId
LEFT OUTER JOIN EmailVoting
ON EmailAlerts.EmailAlertID = EmailVoting.EmailAlertID
AND EmailVoting.UserId = EmailStats.UserId
Where EmailAlerts.EmailAlertID = 43 AND EmailStats.IsTestSend = 0
The SQL is returning the correct data with the EmailVoting fields null if the rows don't exist. Below is the LINQ I currently have:
from ea in db.EmailAlerts
join es in db.EmailStats on ea.EmailAlertID equals es.EmailAlertID
join ud in db.UserDetails on es.UserId equals ud.UserId
join ev in db.EmailVoting on ea.EmailAlertID equals ev.EmailAlertID into vm
from v in vm.DefaultIfEmpty()
join ev in db.EmailVoting on es.UserId equals ev.UserId into udItems
from u in udItems.DefaultIfEmpty()
where v.EmailAlertID == emailAlertID
What I thought was the same in LINQ, isn't displaying correctly and is in fact displaying an entry with a different EmailAlertID. Anyone see where I might be going wrong?
Thanks
Try this:
from ea in db.EmailAlerts
join es in db.EmailStats on ea.EmailAlertID equals es.EmailAlertID
join ud in db.UserDetails on es.UserId equals ud.UserId
join ev in db.EmailVoting on new {ev.EmailAlertID, ev.UserId} equals new {ea.EmailAlertID, es.UserId} into vm
from v in vm.DefaultIfEmpty()
where v.EmailAlertID == emailAlertID
Related
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;
So I have a SQL query that I would like to convert to LINQ.
Here is said query:
SELECT *
FROM DatabaseA.SchemaA.TableA ta
LEFT OUTER JOIN DatabaseA.SchemaA.TableB tb
ON tb.ShipId = ta.ShipId
INNER JOIN DatabaseA.SchemaA.TableC tc
ON tc.PostageId= tb.PostageId
WHERE tc.PostageCode = 'Package'
AND ta.MailId = 'Specification'
The problem I am struggling with is I cannot seem to figure out how to do a left join in LINQ before an inner join, since doing a left join in LINQ is not as clear to me at least.
I have found numerous examples of a LINQ inner join and then a left join, but not left join and then inner join.
If it helps, here is the LINQ query I have been playing around with:
var query = from m in tableA
join s in tableB on m.ShipId equals s.ShipId into queryDetails
from qd in queryDetails.DefaultIfEmpty()
join p in tableC on qd.PostageId equals p.PostageId
where m.MailId == "Specification" && p.PostageCode == "Package"
select m.MailId;
I have tried this a few different ways but I keep getting an "Object reference not set to an instance of an object" error on qd.PostageId.
LINQ is very new to me and I love learning it, so any help on this would be much appreciated. Thanks!
From my SQL conversion recipe:
JOIN conditions that aren't all equality tests with AND must be handled using where clauses outside the join, or with cross product (from ... from ...) and then where
JOIN conditions that are multiple ANDed equality tests between the two tables should be translated into anonymous objects
LEFT JOIN is simulated by using into joinvariable and doing another from from the joinvariable followed by .DefaultIfEmpty().
The order of JOIN clauses doesn't change how you translate them:
var ans = from ta in TableA
join tb in TableB on ta.ShipId equals tb.ShipId into tbj
from tb in tbj.DefaultIfEmpty()
join tc in TableC on tb.PostageId equals tc.PostageId
where tc.PostageCode == "Package" && ta.MailId == "Specification"
select new { ta, tb, tc };
However, because the LEFT JOIN is executed before the INNER JOIN and then the NULL PostageIds in TableB for unmatched rows will never match any row in TableC, it becomes equivalent to an INNER JOIN as well, which translates as:
var ans2 = from ta in tableA
join tb in tableB on ta.ShipId equals tb.ShipId
join tc in tableC on tb.PostageId equals tc.PostageId
where tc.PostageCode == "Package" && ta.MailId == "Specification"
select new { ta, tb, tc };
Use:
var query = from m in tableA
join s in tableB on m.ShipId equals s.ShipId
join p in tableC on s.PostageId equals p.PostageId
where m.MailId == "Specification" && p.PostageCode == "Package"
select m.MailId;
Your query uses a LEFT OUTER JOIN but it doesn't need it.
It will, in practice, function as an INNER JOIN due to your tc.PostageCode = 'Package' clause. If you compare to a column value in a table in a WHERE clause (and there are no OR clauses and you aren't comparing to NULL) then effectively all joins to get to that table will be treated as INNER).
That clause will never be true if TableB is null (which is why you use LEFT OUTER JOIN vs INNER JOIN) - so you should just use an INNER JOIN to make the problem simpler.
How to convert store procedure to linq in nopCommerce c#
My store procedure query
SELECT p.Id
FROM Product p WITH (NOLOCK)
LEFT JOIN Discount_AppliedToProducts dap WITH (NOLOCK)
ON p.Id = dap.Product_Id
LEFT JOIN Product_Category_Mapping pcm WITH (NOLOCK)
ON p.Id = pcm.ProductId
LEFT JOIN Discount_AppliedToCategories dac WITH (NOLOCK)
ON pcm.CategoryId = dac.Category_Id
AND dac.Category_Id IN (1 ,2 ,3 ,4 ,5 ,6)
LEFT JOIN Product_Manufacturer_Mapping pmm WITH (NOLOCK)
ON p.Id = pmm.ProductId
LEFT JOIN Discount_AppliedToManufacturers dam WITH (NOLOCK)
ON pmm.ManufacturerId = dam.Manufacturer_Id
WHERE dap.Discount_Id IN (3)
OR dac.Discount_Id IN (3)
OR dam.Discount_Id IN (3)
My linq query
var productlist = (from q in _productRepository.Table
select q).ToList();
var discount_AppliedToProductIds = (from dp in _discountRepository.Table
from p in dp.AppliedToProducts
select p).ToList().DistinctBy(d => d.Id).ToList();
var discount_AppliedToCategorieIds = (from dp in _discountRepository.Table
from c in dp.AppliedToCategories
select c).ToList().DistinctBy(d => d.Id).ToList();
var discount_AppliedToManufacturerIds = (from dp in _discountRepository.Table
from m in dp.AppliedToManufacturers
select m).ToList().DistinctBy(d => d.Id).ToList();
var product_Manufacturer_Mapping = (from dp in productlist
from pm in dp.ProductManufacturers
select pm).ToList().DistinctBy(d => d.Id).ToList();
var product_Category_Mapping = (from dp in productlist
from pc in dp.ProductCategories
select pc).ToList().DistinctBy(d => d.Id).ToList();
var ss = (from p in productlist
join dap in discount_AppliedToProductIds on p.Id equals dap.Id
join pcm in product_Category_Mapping on p.Id equals pcm.ProductId
//join dac in discount_AppliedToCategorieIds on pcm.CategoryId equals dac.Id
from dac in discount_AppliedToCategorieIds
join pmm in product_Manufacturer_Mapping on p.Id equals pmm.ProductId
join dam in discount_AppliedToManufacturerIds on pmm.ManufacturerId equals dam.Id
from dapd in dap.AppliedDiscounts
from pacd in dac.AppliedDiscounts
from damd in dam.AppliedDiscounts
where discountIds.Any(d => dapd.Id == d || d == pacd.Id || d == damd.Id)
// innner join condition
where categoryIds.Any(d => d == dac.Id) && dac.Id == pcm.CategoryId
select p).ToList();
I have write this code into c# but this code not provide proper result. Now I don't know what is problem into this code. If I run this code into sql server, then I get proper result, but in c# code I don't get proper result.
It's been a long time since I wrote a query in LINQ, but I seem to recall that if you wish to model a LEFT JOIN, you have to use DefaultIfEmpty(), otherwise you end up with an INNER JOIN.
See this, it's answer shows where to apply DefaultIfEmpty:
Linq join iquery, how to use defaultifempty
Obviously if you don't correctly model a LEFT JOIN expression, you'll end up with results only when all 3 inputs produce values.
I would also suggest not using .ToList() on each of your source queries, because that's going to manifest data into memory and use LINQ to Objects for your final query. If you remove the .ToList(), LINQ will construct a single database query for the entire process.
Mark
This question already has answers here:
LINQ - Left Join, Group By, and Count
(5 answers)
Closed 9 years ago.
I am working with entity framework 4.5. I have to convert an SQL query to entity query:
SELECT Customer.CustCode, Invoice.InvoiceId, Invoice.BatchNumber, Invoice.InvoiceDate, Invoice.AdjustFlag, Invoice.InvoiceAmount,
Invoice.InvoiceNote, Invoice.AmountPaid, Customer.BillingContact, Customer.BillingCompany, Customer.BillingStreet1,
Customer.BillingStreet2, Customer.BillingCity, Customer.BillingState, Customer.BillingZip, [Order].PickupDate, [Order].OrderNumber,
[Order].OrderTotal, [Order].ProNumber, [Order].PickupCompany, [Order].PickupCity, [Order].PickUpState, [Order].Dcompany,
[Order].Dcity, [Order].Dstate, CONVERT(varchar(5), DeliverInTime, 114) AS DelInTime, [Order].PiecesWeight1, [Order].BaseRATE,
[Order].POD, [Order].Requester, [Order].Po1, [Order].Po2, AccessorialCharge.Description,
OrderDriverExtraCharge.AccessorialChargeDesc, OrderDriverExtraCharge.AccessorialChargeAmount, [Order].NormalDiscount,
- 1 * [Order].DISCAmount AS DISCAmount
FROM (((Invoice INNER JOIN
[Order] ON Invoice.InvoiceId = [Order].InvoiceId) INNER JOIN
Customer ON Invoice.CustID = Customer.CustID) LEFT JOIN
OrderDriverExtraCharge ON [Order].OrderNumberId = OrderDriverExtraCharge.OrderNumberId) LEFT JOIN
AccessorialCharge ON OrderDriverExtraCharge.AccessorialChargeId = AccessorialCharge.AccessorialChargeId
where Invoice.InvoiceId = '1117782'
If I change OrderDriverExtraCharge.OrderNumberId) LEFT JOIN to OrderDriverExtraCharge.OrderNumberId) JOIN (simple join) or inner join it's not showing the right result.
I have tried this:
from I in db.Invoices
join O in db.Orders on I.InvoiceId equals O.InvoiceId
join C in db.Customers on I.CustId equals C.CustId
join OD in db.OrderDriverExtraCharges on O.OrderNumberId equals OD.OrderNumberId
join AC in db.AccessorialCharges on OD.AccessorialChargeId equals AC.AccessorialChargeId
where I.InvoiceId == invoice.InvoiceId
select new PrintInvoiceViewModel()
But it is not showing the required results. Please help me, I will mark your answer if it worked for me. Thank you.
You can do this:
from I in db.Invoices
join O in db.Orders on I.InvoiceId equals O.InvoiceId
join C in db.Customers on I.CustId equals C.CustId
from OD in db.OrderDriverExtraCharges
.Where(w=>w.OrderNumberId==O.OrderNumberId).DefaultIfEmpty()
from AC in db.AccessorialCharges
.Where(w=>w.AccessorialChargeId==OD.AccessorialChargeId).DefaultIfEmpty()
where I.InvoiceId == invoice.InvoiceId
select new PrintInvoiceViewModel()
Your should use DefaultIfEmpty method, which returns the elements of an IEnumerable<T>, or a default valued singleton collection if the sequence is empty:
from I in db.Invoices
join O in db.Orders on I.InvoiceId equals O.InvoiceId
join C in db.Customers on I.CustId equals C.CustId
join OD in db.OrderDriverExtraCharges on O.OrderNumberId equals OD.OrderNumberId into ODs
from OD in ODs.DefaultIfEmpty()
join AC in db.AccessorialCharges on OD.AccessorialChargeId equals AC.AccessorialChargeId into ACs
from AS in ACs.DefaultIfEmpty()
where I.InvoiceId == invoice.InvoiceId
select new PrintInvoiceViewModel()
Id like to perform an outer join with the second join statement in this query, I keep getting weird errors! (it must be the 3rd RedBull)
var Objeto = from t in Table1.All()
join su in table2.All() on t.Id equals su.Id
join tab2 in Table1.All() on t.PId equals tab2.Id //<-I want it here
select new
{
t.Field1,
SN = su.Field123,
PTN = tab2.FieldABC
};
Any help would be appreciated.
[Edit] - I neglected to say that I'm using SubSonic 3.0, the bug seems to be with SubSonic.....
Performing an outer join requires two steps:
Convert the join into a group join with into
Use DefaultIfEmpty() on the group to generate the null value you expect if the joined result set is empty.
You will also need to add a null check to your select.
var Objeto = from t in Table1.All()
join su in table2.All() on t.Id equals su.Id
join tab2 in Table1.All() on t.PId equals tab2.Id into gj
from j in gj.DefaultIfEmpty()
select new
{
t.Field1,
SN = su.Field123,
PTN = (j == null ? null : j.FieldABC)
};