views:

231

answers:

2

Hi All,

I have a model where a Product can have multiple PriceDrops. I'm trying to generate a list of products with the most recent price drops.

Getting the most recent price drops with the products loaded is easy enough, and I thought it would be the best way to start:

dlo.LoadWith<PriceDrop>(pd => pd.Product);
db.LoadOptions = dlo;
return db.PriceDrops.OrderBy(d=>d.CreatedTime);

Works great for a list of recent price drops, but I want a list of products. If I append a ".Select(d=>d.Product)" I get a list of Products back - which is perfect - but they are no longer associated with the PriceDrops. That is, if I call .HasLoadedOrAssignedValues on the products, it returns false. If I try to interrogate the Price Drops, it tries to go back to the DB for them.

Is there a way around this, or do I have to craft a query starting with Products and not use the Select modifier? I was trying to avoid that, because in some cases I want a list of PriceDrops, and I wanted to re-use as much logic as possible (I left out the where clause and other filter code from the sample above, for clarity).

Thanks, Tom

+1  A: 

Try loading the Products, ordered by their latest PriceDrop:

dlo.LoadWith<Product>(p => p.PriceDrops);
db.LoadOptions = dlo;
return db.Products.OrderBy(d => d.PriceDrops.Max(pd => pd.CreatedTime));

I understand from your question that you're trying to avoid this, why?

Avish
Thanks, I'll just do that. I was trying to avoid it because I wanted to re-use the same filtering logic (multiple where clauses) when I was querying PriceDrops as when I'm querying Products. I omitted those clauses for clarity.
tlianza
I think you could still pass around shared Expression instances that represent the filtering logic, and just use them at the right place.
Avish
A: 

I think what you need here is the the AssociateWith method, also on the DataLoadOptions class.

dlo.AssociateWith<Product>(p => p.PriceDrops.OrderBy(d=>d.CreatedTime))
Samuel Jack