Linq to Entities左外连接分组为一个集合

时间:2014-04-08 14:09:14

标签: c# linq entity-framework linq-to-entities

from component in Materials.OfType<Container>().Where(m => m.Active)
join segmentFinanceRating in segmentFinanceRatingView on component.Id equals segmentFinanceRating.MaterialId into segmentFinanceRatingGroup
from segmentFinanceRatingWithDefault in segmentFinanceRatingGroup.DefaultIfEmpty()
select new
{
   id = component.Id,
   name = component.Name,
   subType = component.SubType,
   size = component.Size,
   MaterialIds = component.Materials.Select(x => x.Id),
   BrandNames = component.Brands.Select(x => x.Name),
   SegmentRatings = segmentFinanceRatingWithDefault
}

我有上面的LINQ to Entities查询,它有一个LEFT JOIN来获取给定组件的一个或多个段的评级值。

segmentFinanceRating实体具有属性{ MaterialId, SegmentId, Rating, LowRated }

目前,结果未分组到相关组件,即SegmentRatings属性不是segmentFinanceRating个对象的单个集合,而是我有多个数据行,其中1 segmentFinanceRating每个对象。

我已经看到了一些使用group x by y into z的示例,但我无法使其正常工作,可能是由于我需要的组件上的一些集合,我也不确定。< / p>

对于如何做到这一点,我们将不胜感激。谢谢。

2 个答案:

答案 0 :(得分:1)

列表中的GroupBy对你不起作用吗?

var list = (from component in Materials.OfType<Container>().Where(m => m.Active)
join segmentFinanceRating in segmentFinanceRatingView on component.Id equals segmentFinanceRating.MaterialId into segmentFinanceRatingGroup
from segmentFinanceRatingWithDefault in segmentFinanceRatingGroup.DefaultIfEmpty()
select new
{
   id = component.Id,
   name = component.Name,
   subType = component.SubType,
   size = component.Size,
   MaterialIds = component.Materials.Select(x => x.Id),
   BrandNames = component.Brands.Select(x => x.Name),
   SegmentRatings = segmentFinanceRatingWithDefault
}).ToList().GroupBy(s=> s.SegmentRatings);

答案 1 :(得分:0)

在这种情况下,以匿名类型进行连接要容易得多:

from component in Materials.OfType<Container>().Where(m => m.Active)
select new
{
   id = component.Id,
   name = component.Name,
   subType = component.SubType,
   size = component.Size,
   MaterialIds = component.Materials.Select(x => x.Id),
   BrandNames = component.Brands.Select(x => x.Name),
   SegmentRatings = (from segmentFinanceRating in segmentFinanceRatingView
                     where segmentFinanceRating.MaterialId == component.Id
                     select segmentFinanceRating)
}

当特定组件没有时,您将拥有SegmentRatings的空集合,与外连接具有相同的效果。