2012-10-23 84 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(); 
} 

做工精细:)

相关问题