tags:

views:

177

answers:

2

I have the following SQL , how do I implement this in LINQ (c# please :))

SELECT     a.Category, a.Description, a.Item, a.[Value], a.Loading, a.MaxDiscount, MIN(b.EffectiveDate) AS FromDate, a.EffectiveDate AS EndDate, a.SortOrder,  a.ID
FROM List a   
LEFT OUTER JOIN List b ON a.[Value] = b.[Value] AND a.Category = b.Category AND a.Description = b.Description AND a.Item = b.Item AND a.EffectiveDate < b.EffectiveDate  
GROUP BY a.Category, a.Description, a.Item, a.[Value], a.Loading, a.MaxDiscount, a.SortOrder, a.EffectiveDate, a.ID  
HAVING      (a.Category = 'General') AND (a.Description = 'Cover') AND (a.EffectiveDate <= CONVERT(DATETIME, '2009-04-01 00:00:00', 102)) AND (MIN(b.EffectiveDate) >= CONVERT(DATETIME, '2009-04-01 00:00:00', 102) OR MIN(b.EffectiveDate) IS NULL) AND (a.Item = 'Type')
ORDER BY a.SortOrder

I have the following (using SubSonic Linq)

var query = from a in List.All() join b in List.All() 
            on new {a.Value,a.Category ,a.Description,a.Item} 
            equals new {b.Value,b.Category ,b.Description,b.Item} into temp

I have no idea how to add the a.EffectiveDate < b.EffectiveDate at the moment

A: 

I would suggest you to create SP (Stored procedure) for your query and include that SP in DBML file, with that you can access/call it as method from DataContext object.

After all code is for humans to understand, keep is as simple as possible :)

Click here for more on "How to call Stored procedure in LINQ"

Prashant
A: 

If you don't join, you don't have to regroup. If you don't join, you don't have to have a funny on clause.

All you want to do is filter, so all you should do is 'where'.

someDate = new DateTime(2009, 4, 1);

var query = 
from a in List
where a.Category == "General"
where a.Description == "Cover"
where a.Item == "Type"
where a.EffectiveDate < someDate
let minDate =
(
  from b in List
  where a.Value == b.Value
  where a.Category == b.Category
  where a.Description == b.Description
  where a.Item == b.Item
  where a.EffectiveDate < b.EffectiveDate
  orderby b.EffectiveDate
  select new DateTime? ( b.EffectiveDate )
).FirstOrDefault()
where !minDate.HasValue || someDate < minDate.Value
orderby a.SortOrder
select a;
David B
not sure an on clause is 'funny'.
John Nicholas
http://dilbertblog.typepad.com/the_dilbert_blog/2007/07/subjective-humo.html
David B