I have a query that combines a join and a group, but I have a problem. The query is like:
var result = from p in Products
join bp in BaseProducts on p.BaseProductId equals bp.Id
group p by p.SomeId into pg
select new ProductPriceMinMax {
SomeId = pg.FirstOrDefault().SomeId,
CountryCode = pg.FirstOrDefault().CountryCode,
MinPrice = pg.Min(m => m.Price),
MaxPrice = pg.Max(m => m.Price),
BaseProductName = bp.Name <------ can't use bp.
};
As you see, it joins the Products table with the BaseProducts table, and groups on an id of the Product table. But in the resulting ProductPriceMinMax, I also need a property of the BaseProducts table: bp.Name, but it doesn't know bp.
Any idea what I'm doing wrong?
Thanks!
I met the same problem as you.
I push two
tables
result
intot1
object and groupt1
.We did it like this:
EDIT: we used the version of AakashM, because it has better performance
Once you've done this
you no longer have access to the range variables used in the initial
from
. That is, you can no longer talk aboutp
orbp
, you can only talk aboutpg
.Now,
pg
is a group and so contains more than one product. All the products in a givenpg
group have the sameSomeId
(since that's what you grouped by), but I don't know if that means they all have the sameBaseProductId
.To get a base product name, you have to pick a particular product in the
pg
group (As you are doing withSomeId
andCountryCode
), and then join toBaseProducts
.That said, this looks pretty unusual and I think you should step back and consider what you are actually trying to retrieve.