2015-11-03 106 views
2

在我的数据结构时,选择这两个父母和孩子的项目,我有以下类别:查询子属性

public partial class Item 
{ 
    // stuff 
    public int QuoteId { get; set; } 
    public virtual ItemType ItemType { get; set; } 
} 

public partial class ItemType 
{ 
    //stuff 
    public virtual ICollection<Item> Items { get; set; } 
} 

我想要做的就是让所有的ItemTypes的列表,每个都有其项目根据QuoteId填充集合。

因此,例如,如果有三个项目类型,其中只有两个有50报价编号项目:

  • ItemType1
    • Item.QuoteId == 50
  • ItemType2
  • ItemType3
    • Item.QuoteId == 50

我已经成功地获得了接近与此查询:

r.ItemTypes.Select(x => x.Items.Where(i => i.QuoteId == CurrentQuote.QuoteId)); 

但是这给你(正如您所料,因为我Select ing Item)是IEnumerable<IEnumerable<Item>>。这有我后面的结构,但没有ItemType数据。

我意识到这是一个愚蠢的问题,但我很沮丧,我无法得到答案。

回答

9
r.ItemTypes.Where(x => x.Items.Any(i => i.QuoteId == CurrentQuote.QuoteId)); 

如果你需要得到每一个都ItemTypes,只有特定的项目,你可以这样做:

r.ItemTypes.Select(x => new 
{ 
    x, 
    FilteredItems = x.Items.Where(i => i.QuoteId == CurrentQuote.QuoteId) 
}); 

之后,你需要分配x.ItemsFilteredItems为每个ItemType的

+0

没有。感谢您的帮助,但我已经尝试过。它给了我一个项目列表。我需要一个ItemTypes列表。显然没有很好地解释我自己。 –

+0

@MattThrower尝试更新 – Backs

+0

谢谢 - 但是,我需要获取* all * ItemTypes,无论它们是否具有项目。 SQL等价物将是一个左连接。对不起 - 我觉得我已经很糟糕地解释了自己。 –

2

你必须选择Item.ItemType属性,如果您想要给定QuoteId的所有ItemType。您还可以使用SelectMany扁平化“嵌套”集合:

IEnumerable<ItemType> types = r.ItemTypes 
    .SelectMany(x => x.Items.Where(i => i.QuoteId == CurrentQuote.QuoteId) 
          .Select(i => i.ItemType)); 

如果你不感兴趣的嵌套ItemType(不知道逻辑),可以使用Backs' approach

IEnumerable<ItemType> types = r.ItemTypes 
    .Where(x => x.Items.Any(i => i.QuoteId == CurrentQuote.QuoteId)); 
0
var result = from itemTypes in r.ItemTypes 
      where itemTypes.QuoteId equals CurrentQuote.QuoteId 
      select new {itemType = itemTypes}