Why can't I select data from my LINQ sub query join? - c#

I am trying to get data from 2 tables using a left join to a nested query. This allows me to get data from Item table but not the cart(nested query) table:
var q = from s in db.Items
join sub in (from c in db.Carts
where c.CartID == 1
group c by c.ItemID into g
select new
{
ItemID = g.Key,
Qty = g.Select(s => s.Qty)
}) on s.ItemID equals sub.ItemID into a
select new ItemViewModel
{
CategoryID = s.CategoryID,
Description = s.Description,
Price = s.Price,
**This being the issue------>>>>>>>** //Qty = a.Select(j => j.Qty),
ItemID = s.ItemID,
ItemName = s.ItemName
};
viewModel = q.ToList();
The query i am trying to acheive is:
select Items.*, Cart.Qty
from Items
left join (select ItemID, Qty from carts where CartID = 1 ) Cart
on Items.ItemID = Cart.ItemID

You can use GroupJoin with SelectMany for LEFT JOIN SQL Query and get the desired output.
var result = db.Items.GroupJoin(db.Carts.Where(x => x.CartID == 1), item => item.ItemID, cart => cart.ItemID,
(item, cart) => new { item, cart })
.SelectMany(x => x.cart.DefaultIfEmpty(), (it, ca) =>
{
return new ItemViewModel
{
ItemName = it.item.ItemName,
Price = it.item.Price,
ItemID = it.item.ItemID,
// ... .... ....
// Fill the required columns from it.Item property..
Qty = ca != null ? ca.Qty : 0
};
}).ToList();
EDIT: The LINQ version with SelectMany.
var result = from s in db.Items
join sub in (from c in db.Carts
where c.CartID == 1
select c)
on s.ItemID equals sub.ItemID into joined
from row in joined.DefaultIfEmpty()
select new ItemViewModel
{
CategoryID = s.CategoryID,
Description = s.Description,
Price = s.Price,
Qty = row != null ? row.Qty : 0,
ItemID = s.ItemID,
ItemName = s.ItemName
};
The C# Fiddle with sample data.

If I'm understanding correctly, and assuming that ItemViewModel.Qty property is just an int, the simplest form of the query you want is:
var q = from item in items
join cart in
(from cart in carts where cart.CartID == 1 select cart)
on item.ItemID equals cart.ItemID into itemCarts
select new ItemViewModel
{
ItemID = item.ItemID,
Qty = itemCarts.Sum(cart => cart.Qty)
};
If you want to only slightly modify/fix your query:
var q = from s in db.Items
join sub in (from c in db.Carts
where c.CartID == 1
group c by c.ItemID into g
select new
{
ItemID = g.Key,
Qty = g.Sum(s => s.Qty)
// or Qty = g.Select(s => s.Qty)
// and below: Qty = a.SelectMany(x => x.Qty).Sum()
})
on s.ItemID equals sub.ItemID into a
select new ItemViewModel
{
CategoryID = s.CategoryID,
Description = s.Description,
Price = s.Price,
Qty = a.Sum(x => x.Qty),
ItemID = s.ItemID,
ItemName = s.ItemName
};

Related

LINQ GroupBy a name, but how to get Id of users?

I want to display how many transfers did every customer.
I want to display CustomerId, Name and Totaly amount of transfers.
I mean I want to display CustomerId too, not only Name and Amount transfers.
Everything works fine except CustomerId: it is empty in my DataGridview.
I don't know how to do and I would really appreciate any kind of help.
Here is my code:
using (Db db = new Db())
{
var statistic = (from u in db.Transfers
join c in db.Customers on u.CustomerId equals c.CustomerId
where u.IsActive == true && u.Paid == true
group u by c.FirstName into g
select new
{
// here I get Headertext but not Id's value
Id = g.Select(x =>x.CustomerId),
Name = g.Key,
Totaly = g.Sum(x => x.Amount)
}).OrderByDescending(x => x.Totaly).ToList();
if (statistic != null)
{
dgvCustomerList.DataSource = statistic;
}
}
The correct way is to group it by CustomerId (because CustomerId is unique, you will get distinct customers inside select and then you can use FirstOrDefault() for getting FirstName property):
using (Db db = new Db())
{
var statistic = (from u in db.Transfers
join c in db.Customers on u.CustomerId equals c.CustomerId
where u.IsActive == true && u.Paid == true
group u by c.CustomerId into g
select new
{
Id = g.Key, // here I get Headertext but not Id's value
Name = g.FirstOrDefault().FirstName,
Totaly = g.Sum(x => x.Amount)
}).OrderByDescending(x => x.Totaly).ToList();
if (statistic != null)
{
dgvCustomerList.DataSource = statistic;
}
}
You can group by both customerId and FirstName
using (Db db = new Db())
{
var statistic = (from u in db.Transfers
join c in db.Customers on u.CustomerId equals c.CustomerId
where u.IsActive == true && u.Paid == true
group u by new {key c.FirstName,key c.CustumerId} into g
select new
{
Id = g.Key.CustumerId,//g.Select(x =>x.CustomerId), // here I get Headertext but not Id's value
Name = g.Key.FirstName,
Totaly = g.Sum(x => x.Amount)
}).OrderByDescending(x => x.Totaly).ToList();
if (statistic != null)
{
dgvCustomerList.DataSource = statistic;
}
}

How to get record with max date with join?

How can I do this in LINQ?
select MAX(d.DepartureDateRange),MAX(d.ReturnDateRange)
from Tour t join
TourCategory tc on t.ID = tc.TourID
join TourDates td on t.ID = td.TourID
join Dates d on d.ID = td.DatesID
where tc.CategoryID = 3 and t.ID = 12
Database diagram is here ->
For example joins is like this but i cannot get Max of DepartureDateRange & ReturnDateRange
var query2 = from t in db.Tour
join tc in db.TourCategory on t.ID equals tc.TourID
join td in db.TourDates on t.ID equals td.TourID
join d in db.Dates on td.DatesID equals d.ID
where tc.CategoryID == 3
select new IndexTour
{
ID = t.ID,
TourName = t.TourName,
//DepartureDateRange =
//ReturnDateRange =
Description = t.SmallDesc,
Price = t.Price,
CoverPhotoUrl = t.CoverPhotoUrl,
TourProgram = t.TourDesc
};
Thanks in advance.
Here it is (dates are grouped by Tour):
var query2 =
from t in db.Tour
join tc in db.TourCategory on t.ID equals tc.TourID
where tc.CategoryID == 3
// join dates aggregates grouped by tour id
join tdates in
from td in db.TourDates
join d in db.Dates on td.DatesID equals d.ID
group d by td.TourID into grp
select new
{
tourID = grp.Key,
departure = grp.Max(g => g.DepartureDateRange),
rtrn = grp.Max(g => g.ReturnDateRange)
}
on t.ID equals tdates.tourID
select new IndexTour
{
ID = t.ID,
TourName = t.TourName,
DepartureDateRange = tdates.departure,
ReturnDateRange = tdates.rtrn,
Description = t.SmallDesc,
Price = t.Price,
CoverPhotoUrl = t.CoverPhotoUrl,
TourProgram = t.TourDesc
};
I think this is what you want?
var dateRanges = tours
.Join(tourCategories,
t => t.Id,
tc => tc.TourId,
(t, tc) => (t, tc))
.Join(tourDates,
ttc => ttc.t.Id,
td => td.TourId,
(ttc, td) => (ttc, td))
.Join(dates,
ttctd => ttctd.td.DateId,
d => d.Id,
(ttctd, d) =>
new {
TourId = ttctd.ttc.t.Id,
CategoryId = ttctd.ttc.tc.CategoryId,
DepartureDateRange = d.DepartureDateRange,
ReturnDateRange = d.ReturnDateRange
});
var filtered = dateRanges
.Where(r => r.CategoryId == 3 && r.TourId == 12);
var maxDepartureDateRange = filtered.Max(d => d.DepartureDateRange);
var maxReturnDateRange = filtered.Max(d => d.ReturnDateRange);

join with multiple group by element and select extra columns

Can you please help to convert this from sql to linq, i am new to linq and been trying this and couldn't succeed. Let me know if this is even possible or not?
SELECT max(Products.ProductID) as ProductID, Products.SKU, Products.Name, Products.RRP, Products.Price,
max(Products.FrontTall) as FrontTall,
ProductsCategory.SortOrder,
Products.ColorValue,
max(Products.ColorImg) as ColorImg,
Products.IsPrimary,
Products.Visible
FROM Products INNER JOIN ProductsCategory ON Products.ProductID = ProductsCategory.ProductID
WHERE (ProductsCategory.CategoryID = 5 ) AND (Products.Visible = 1) AND (Products.Inactive = 0) AND (Products.Deleted = 0 or Products.Deleted is null)
GROUP BY SKU, Products.Name, RRP, Price, ColorValue, ProductsCategory.SortOrder, IsPrimary, Visible
AND this is what i am trying
var products = (from p in db.Products
join cp in db.ProductsCategories on p.ProductID equals cp.ProductID
where cp.CategoryID == catId && p.Visible == true && p.Inactive == false && (p.Deleted == null || p.Deleted == false)
group p by new {
p.SKU,
p.Name,
p.RRP,
p.Price,
p.ColorValue,
p.IsPrimary,
p.Visible,
cp.SortOrder
} into grouped
select new {
ProductID,
FrontTall,
ColorImg,
SKU = grouped.Key.SKU,
Name = grouped.Key.Name,
RRP = grouped.Key.RRP,
Price = grouped.Key.Price,
ColorValue = grouped.Key.ColorValue,
IsPrimary = grouped.Key.IsPrimary,
Visible = grouped.Key.Visible,
SortOrder = grouped.Key.SortOrder
})
.OrderBy(x => x.SortOrder);
I need to get the ProductID, FrontTall and ColorImg field value without including in group by
Thanks in advance.
Kish
select new {ProductID = grouped.Max(x => x.ProductID)}

Self Join in Linq with null values c#

How can i get the rows that have null in the column used for self join ?
My code is :
IEnumerable<ListClassView> list = from l in lists join lp in lists on
l.ParentListId equals lp.Id
select new ListClassView()
{
Id = l.Id,
ListName = l.ListName,
Description = l.Description,
ParentName = lp.ListName,
IsActive = l.IsActive
};
I am unable to fetch rows where ParentListId=null. Is there a way where i can get all rows ?
Alternative syntax:
var list = lists.GroupJoin(
lists,
l => l.ParentListId,
lp => lp.Id,
(l, lp) => new ListClassView
{
Id = l.Id,
ListName = l.ListName,
Description = l.Description,
ParentName = lp.FirstOrDefault() == null ? null : lp.First().ListName,
IsActive = l.IsActive
});
I found the solution from here by applying a left join :
IEnumerable<ListClassView> list = from l in lists join lp in lists on
l.ParentListId equals lp.Id into lpp
from p in lpp.DefaultIfEmpty()
select new ListClassView()
{
Id = l.Id,
ListName = l.ListName,
Description = l.Description,
ParentName = p.ListName,
IsActive = l.IsActive
};
Now, It gets all rows including those with ParentListId = null

Not counting null values from a linq LEFT OUTER JOIN query

I have this sql query that does exactly what i want but i need it in linq. It returns a few AVC rows and counts how many PersonAVCPermission that has status 1 linked to it
SELECT a.Id, a.Name, a.Address, COUNT(p.AVCID) AS Count
FROM AVC AS a
LEFT OUTER JOIN
(
SELECT PersonAVCPermission.AVCId
FROM PersonAVCPermission
WHERE PersonAVCPermission.Status = 1
) AS p
ON a.Id = p.AVCId
GROUP BY a.Id, a.Name, a.Address
I have this query in linq and it does the same thing except when there are no PersonAVCPermission it still counts 1
var yellows = odc.PersonAVCPermissions.Where(o => o.Status == (int)AVCStatus.Yellow);
var q = from a in odc.AVCs
from p in yellows.Where(o => o.AVCId == a.Id).DefaultIfEmpty()
group a by new { a.Id, a.Name, a.Address } into agroup
select new AVCListItem
{
Id = agroup.Key.Id,
Name = agroup.Key.Name,
Address = agroup.Key.Address,
Count = agroup.Count(o => o.Id != null)
};
Im guessing that with DefaultIfEmpty() it places null rows in the list that then gets counted so i try to exclude them with (o => o.Id != null) but it still counts everything as at least one
If i dont use DefaultIfEmpty() it skips the rows with count 0 completely
How can i exclude them or am i doing it completely wrong?
How about using .Any() and a Let?
var yellows = odc.PersonAVCPermissions.Where(o => o.Status == (int)AVCStatus.Yellow);
var q = from a in odc.AVCs
let Y = (from p in yellows.Where(o => o.AVCId == a.Id) select p).Any()
where Y == true
group a by new { a.Id, a.Name, a.Address } into agroup
select new AVCListItem
{
Id = agroup.Key.Id,
Name = agroup.Key.Name,
Address = agroup.Key.Address,
Count = agroup.Count(o => o.Id != null)
};
You don't need the join, nor the grouping:
var q = from a in odc.AVCs
select new AVCListItem
{
Id = a.Id,
Name = a.Name,
Address = a.Address,
Count = yellows.Where(o => o.AVCId == a.Id).Count()
};

Categories

Resources