如何在LINQ中执行以下操作

时间:2009-07-21 09:47:19

标签: c# sql linq

我有以下SQL,我如何在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

我有以下(使用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 

我不知道如何添加a.EffectiveDate&lt; b.EffectiveDate目前

2 个答案:

答案 0 :(得分:0)

如果您不加入,则无需重新组合。 如果你不加入,你就不必有一个有趣的条款。

你要做的只是过滤,所以你应该做的就是'在哪里'。

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;

答案 1 :(得分:-1)

我建议您为查询创建SP(存储过程)并将该SP包含在DBML文件中,您可以从DataContext对象访问/调用它。

在所有代码供人类理解之后,保持尽可能简单:)

点击此处了解有关"How to call Stored procedure in LINQ"

的更多信息