【问题标题】:LINQ Joining 2 tablesLINQ 连接 2 个表
【发布时间】:2011-09-27 21:23:23
【问题描述】:

我在数据库中有两个表,其中一个包含所有可能的杂货值的列表。例如

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 中,则 selected 被标记为 true: 购物清单.ID Grocerylists.Description 已选中

【问题讨论】:

  • 请张贴您的表格(列)
  • 您的问题有点不清楚......您所说的“我想要一个包含所有可能的杂货商品的结果,其中包含牛奶和奶酪。”是什么意思?你能给我们展示一些示例输出吗?您是否只想列出所有可能的杂货,并带有一个属性说明该商品是否被选中?

标签: linq join entity


【解决方案1】:

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

//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;

如果您想获取有关加入的信息,那么这张图片会对您有所帮助

内连接

外部连接

尝试理解,这可能会帮助您解决您的问题

【讨论】:

    【解决方案2】:

    编辑:听起来你仍然想做左连接。在你的情况下:

    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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-10-03
      • 1970-01-01
      • 1970-01-01
      • 2015-02-28
      • 1970-01-01
      相关资源
      最近更新 更多