2012-10-23 78 views
-2

我在查詢中想要顯示2個表格中的記錄時遇到了一些小問題。我需要從第一表和許多行從第二表(其涉及在第一table.id)如何從第一個表格獲取一行並從第二個表格獲取其他表格

像表1

name | id 
---------- 
Shop | 1 
Shop | 2 

表2

name | id | shopid 
item | 1 | 
item | 2 | 
item | 3 | 

我想顯示一行檢索表1中的單行和表2中的相關行。

我有一個包含兩個表的屬性的項目對象,但我需要顯示錶1中的單個記錄(我有tr通過加入和其他方式,但從表1中獲得更多的值(第1條記錄有信息,其他是空的))。

這裏是示例代碼

public class ItemsInfo 
{ 
    public Shopname { get; set;} 
    public item { get; set; } 
} 

public List<ItemsInfo> ShopItems(int ShopId) 
{ 
    var items = from i in db.items 
       join s in db.shops on i.shopid equals s.id 
       where s.id == ShopId 
       select new ItemsInfo 
          { 
           shopname = s.name, 
          items = i.name 
          } 
    return items.Tolist(); 
} 

欲導致作爲

Shopname : abcd 
items : item 1 
items : item 2 
items : item 3 
+2

你能告訴我們一些樣本數據?該樣本數據的預期結果?你能告訴我們你嘗試過哪些linq查詢是行不通的嗎?它是否已經在實現'IEnumerable '的對象中?如果是這樣,那個對象是什麼? –

+0

第一次嘗試加入第二張表,但沒有成功! –

+0

我已經更新了這個問題請看看 –

回答

1

找到解決方案:)

創建主對象,並加入第二表中的嵌套的對象到主被攝體

這裏是代碼

創建2名對象1店表,第二個的項目

public class Shop 
{ 
    /// Shop Object 
    public string Shop { get; set; } 
    public List<Item> Items { get; set; } 
} 

public class Item 
{ 
    ///Items Object 
    public string Name { get; set; } 
    public string Picture { get; set; } 
} 


public List<Item> ItemsList(int id) 
{ 
    var item = from i in DB.Items 
    where i.ShopId == id 
    select new ShopItem 
    { 
     Name = i.Name, 
     Picture = i.ItemPictures 
    }; 
    return item.ToList(); 
} 


public List<Shop> ShopItems(int ShopId) 
{ 
    var Shopitms = from shop in DB.Shops 
    where shop.Id == ShopId && shop.IsActive == true && shop.IsDeleted == false 
    select new Shop 
    { 
     Shop = shop.Name, 
     Items = ItemsList(shop.Id) 
    } 
return ShopItms.ToList(); 
} 

做工精細:)

相關問題