Linq嵌套内部联接

时间:2012-07-07 06:20:56

标签: linq linq-to-sql nested-queries linq-query-syntax nested-query

我想加入以下表格

1. B_Book[1st Table]
      -B_BID (Book ID)(PK)
      -B_Name
      -B_CategroyID (FK)
2. BI_BookInstance [2nd Table]
      -BI_IID(Instance ID)
      -BI_BID (FK)
      -BI_Price
3. BC_BookCategory [3rd Table]
      -BC_CategoryID (PK)
      -BC_CategoryName

首先加入B_Book和BI_BookInstance,然后用BookCategory加入两者的结果。 (第一次加入)[B_BID等于BI_BID] (第二次嵌套连接)[第一次连接的结果B_CategoryID等于BC_CategoryID]

修改

SQL将类似于以下内容:

SELECT * FROM
   (SELECT * FROM B_Book b JOIN BI_BookInstance bi on b.B_BID = bi.BI_BID) as t1
   JOIN BC_BookCategoryID bc on bc.BC_CategoryID = t1.B_CategoryID

3 个答案:

答案 0 :(得分:1)

与LINQ中的查询匹配的内容如下(您将注意到与SQL的相似性)。我还提供了一些关于如何重命名返回字段的示例,例如Price或CategoryName:

var results = from b in B_Book
    join bi in BI_BookInstance
    on b.B_BID equals bi.BI_BID
    join bc in BC_BookCategory
    on b.B_CategoryID equals bc.BC_CategoryID
    select new
      {
        // put in whatever fields you want returned here:
    b.B_BID, 
    b.B_CategoryID, 
    b.B_Name,
    bi.BI_BID,
    bi.BI_IID,
    Price = bi.BI_Price,
    bc.BC_CategoryID,
    CategoryName = bc.BC_CategoryName
      };

答案 1 :(得分:0)

我认为内部联接(你的FK不是null),所以我想这样查询:

    var ctx = new YourEntities();

    var query = from b in ctx.B_Book
                from bi in ctx.BI_BookInstance
                from bc in ctx.BC_BookCategory
                where b.B_BID == bi.BI_BID && b.B_CategoryID == bc.BC_CategoryID
                select new 
                {
                    BInstID = bi.BI_IID,
                    BName = b.B_Name,
                    BPrice = bi.BI_Price,
                    BCategory = bc.BC_CategoryName
                };

    foreach (var item in query)
    {
        Console.WriteLine(item.BInstID);
        Console.WriteLine(item.BName);
        Console.WriteLine(item.BPrice);
        Console.WriteLine(item.BCategory);
        Console.WriteLine("");
    } 

答案 2 :(得分:0)

如果导航属性到位,您可以在不明确使用linq的join语句的情况下执行此操作:

from b in ctx.B_Book
from bi in b.BookInstances
select new { b.Property1, bi.Property2, b.BookCategory.Name }