2015-11-03 130 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}