Linq嵌套内部联接



我想加入以下表

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

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

我假设有内部联接(您的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("");
    } 

您可以在不显式使用linq的join语句的情况下执行此操作,前提是导航属性已到位:

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

相关内容

  • 没有找到相关文章

最新更新