I have an invoice and it can contains items called tracks. InvoiceLine is the junction table to connect the two. Everything works fine if an invoice contains at least one track. What I want to achieve is to return the invoice even if it contains no tracks.
My initial code:
var screenset =
from inv in context.Invoices where inv.InvoiceId == invoiceID
join line in context.InvoiceLines on inv.InvoiceId equals line.InvoiceId
join track in context.Tracks on line.TrackId equals track.TrackId
select new InvoiceAndItemsDTO
{
InvoiceId = inv.InvoiceId,
InvoiceDate = inv.InvoiceDate,
InvoiceTotal = inv.Total,
CustomerId = inv.CustomerId,
CustomerFullName = inv.Customer.LastName + ", " + inv.Customer.FirstName,
CustomerPhoneNumber = inv.Customer.Phone,
InvoiceLineId = line.InvoiceLineId,
TrackId = track.TrackId,
TrackName = track.Name,
TrackPrice = track.UnitPrice,
Artist = track.Album.Artist.Name,
UnitPrice = line.UnitPrice,
Quantity = line.Quantity,
Action = "None"
};
The above will return the invoice and tracks correctly if it contains any track.
Basically the above code is an inner join so if there are no tracks the result set will be empty. So I corrected my code to include the invoice even when it contains no tracks.
var screenset =
from inv in context.Invoices where inv.InvoiceId == invoiceID
from j in context.Invoices where j.InvoiceId == invoiceID
join line in context.InvoiceLines on j.InvoiceId equals line.InvoiceId
join track in context.Tracks on line.TrackId equals track.TrackId
select new InvoiceAndItemsDTO
{
InvoiceId = inv.InvoiceId,
InvoiceDate = inv.InvoiceDate,
InvoiceTotal = inv.Total,
CustomerId = inv.CustomerId,
CustomerFullName = inv.Customer.LastName + ", " + inv.Customer.FirstName,
CustomerPhoneNumber = inv.Customer.Phone,
InvoiceLineId = line.InvoiceLineId,
TrackId = track.TrackId,
TrackName = track.Name,
TrackPrice = track.UnitPrice,
Artist = track.Album.Artist.Name,
UnitPrice = line.UnitPrice,
Quantity = line.Quantity,
Action = "None"
};
But I get an empty result:
I tried using join into newset
and using from e in newset.DefaultIfEmpty()
but I am joining 3 tables and join into
produces the last table and cannot include all joined tables.
I appreciate any help on this.
Thanks in advance.