2011-09-27 83 views
1

我在数据库中有两个表,其中包含所有可能的杂货价值清单。例如LINQ加入2个表

Milk 
Cheese 
Bread 
Meat 

第二个表包含从杂货店选择的项目。例如:

Milk 
Cheese 

我想是有牛奶和奶酪中选择所有可能的杂货的结果。

任何想法?

以下是表格。

The GroceryList Table: 
ID INT PK 
Description Varchar(50) 

The ShoppingList Table: 
ID INT PK 
GroceryListID int FK to GroceryList.ID 

因此所产生的实体将成为从GroceryList的所有项目,如果他们在ShoppingList存在,那么选择标记为真: ShoppingList.ID Grocerylists.Description 选择

+1

请发表您的表(列) –

+2

你的问题有点不清楚...你是什么意思?“我想要一个结果,所有可能的食品都选择了牛奶和奶酪。”?你能向我们展示一些样本输出吗?你只是想要一个列出所有可能的杂货的属性,说明该项目是否被选中? –

回答

0

基于理解,你可以做这样的事情

//first get the list of product which satisfy your condition 

    var ids = (from p ShoppingList 
       select p.GroceryListID).ToList(); 

//second filter the Grocery products by using contains 

    var myProducts = from p in GroceryList 
        where ids.Contains(p.ID) 
        Select p; 

,或者如果你想获得

关于加入的信息比这个图片将帮助你

内加入 enter image description here

外部联接 enter image description here

试图理解并可以帮助你解决你的查询

+0

感谢这使我朝着正确的方向前进。我很感激。 – timthacker63

0

编辑:听起来仍然像你想要做一个左连接。你的情况:

var LINQResult = from g in Datacontext.GroceryList 
       from s in DataContext.ShoppingList 
        .Where(c=>c.ID == g.ID) 
        .DefaultIfEmpty() 
       select new { 
        g.ID, 
        g.Description, 
        s.ID // Will be null if not selected. 
        }; 

更多的例子:

Left Join on multiple tables in Linq to SQL