簡體   English   中英

C# LINQ 將多個表連接到一個對象中

[英]C# LINQ Join multiple tables into one object

主要解決問題:

我如何“降低 2 級”以獲得 Owner.Pet[n].Toys 並立即將其全部放入一個對象中。

系統中存在三個實體: OwnerPetToy

我正在嘗試編寫一個查詢(使用 LINQ 的類似 SQL 的表示法),它將給我帶來類Owner的單個對象,其內部屬性已填充 =分配給該所有者的所有寵物 + 每個寵物都有它的所有玩具。

這是我到目前為止所擁有的,它沒有按預期工作。 SQL 感覺告訴我,我在某處缺少 GROUP JOIN ...

var singleOwnerQuery =
    from o in owners
    join p in pets on o.FirstName = p.OwnerName
    join t in toys on p.PetId = t.ToyUniqueId // each toy is unique - there are not "re-usable" toys 
    where o.Name == "..." && o.LastName == "..."
    select new Owner
    {
        Pets = pets // this should already assign all the toys for each of the pets
    };

任何幫助將不勝感激。

我跳過了每個類中的許多其他屬性以使其更簡單

嘗試以下查詢。 沒有模型,這只是指導如何按照您的情況進行預加載查詢。

var singleOwnerQuery =
    from o in owners
    where o.Name == "..." && o.LastName == "..."
    select new Owner
    {
        Pets = pets.Where(p => o.FirstName == p.OwnerName)
          .Select(p => new 
          {
              p.PetId,
              Toys = toys.Where(t => p.PetId == t.ToyUniqueId).ToList()
          })
          .tolist()
    };

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM