Dot-Net

為什麼在簡單的一對多關係上使用 LINQ Join?

  • August 29, 2011

幾年來我一直在使用 LINQ to SQL 和實體框架,並且我總是映射我的數據庫關係以生成相關的導航屬性。而且我總是使用導航屬性。

我錯過了什麼嗎?

如果我有Category->Products一對多類型的關係,我會使用

var redProducts = context.Category.Single(c => c.Name = "red").Products;

我經常看到人們在這個網站、線上項目和其他各種網站上進行手動連接。

var employer = from category in context.Categories
              join product in context.Products
              on category.CategoryId equals product.CategoryId
              where category.Name == "red"
              select product;

所以為什麼?使用這種Join語法有什麼好處?

這通常是一個錯誤。

join@George 是正確的,您的兩個範例在功能上有所不同,但與vs non-無關join。但是你可以很容易地寫:

var redProducts = context.Category
                        .Where(c => c.Name == "red")
                        .SelectMany(c => c.Products);

…與您的範例在功能上相同(但在可讀性和可維護性方面更勝一籌join) 。

引用自:https://stackoverflow.com/questions/7229569