Linq明显的问题

时间:2011-09-19 13:29:07

标签: linq

我是使用LINQ的新手,现在我在带有多个内连接的sql中有一个查询,它工作正常。我试图将其更改为等效的LINQ代码,我能够实现LINQ,除了我在查询中使用的不同事实......

我的查询

select DT.[Name], count(distinct([FeatureControlID])) as [Value], DT.[Weight]
from [DocumentTypes] DT inner join
[DocumentTypesSchema] DTS on
DT.[ID] = DTS.[DocumentTypeID] inner join
ProductsFeaturesControlsDocumentValues [PFCDV] on
DTS.[ID] = PFCDV.[SchemaID]
where [PFCDV].[ProductID] = 72
group by DT.[Name], DT.[Weight], [DT].[ID]
order by [DT].[ID]

我没有Distinct条件的LINQ如下

 from dt in db.DocumentTypes
join dts in db.DocumentTypesSchemas on new { ID = dt.ID } equals new { ID = dts.DocumentTypeID }
join pfcdv in db.ProductsFeaturesControlsDocumentValues on new { ID = dts.ID } equals new { ID = pfcdv.SchemaID }
where
  pfcdv.ProductID == 72
group new {dt, pfcdv} by new {
  dt.Name,
  dt.Weight,
  dt.ID
} into g
orderby
  g.Key.ID
select new  {
  g.Key.Name,
  Value = (Int64?)g.Count(p => p.pfcdv.FeatureControlID != null),
  Weight = (System.Decimal?)g.Key.Weight
}

任何人都可以帮我解决这个问题吗?实际上,linq代码在没有我在代码中使用的Distinct特性的情况下执行。

1 个答案:

答案 0 :(得分:1)

你尝试过这样的事吗?

...
select new  {
  g.Key.Name,
  Value = (Int64?)g.Select(p => p.pfcdv.FeatureControlID)
                   .Where(id => id != null)
                   .Distinct().Count()
  Weight = (System.Decimal?)g.Key.Weight
}