使用 LeftJoin / RightJoin


  Join 方法解析成 SQLINNER JOIN,如果要实现 LEFT JOIN,则需要使用 DefaultIfEmpty 方法来辅助。如下所示:

[TestMethod]
public void TestJoin()
{
    using (var db = new DbContext())
    {
        var query = db.OrderDetails
            .Join(db.Products.DefaultIfEmpty(), d => d.ProductID, p => p.ProductID,
                (d, p) => new { detail = d, product = p });
    }
}

  现在,你可以使用 LeftJoin 方法来替代它(RightJoin也是如此)。如下所示:

[TestMethod]
public void TestLeftJoin()
{
    using (var db = new DbContext())
    {
        var query = db.OrderDetails
            .LeftJoin(db.Product, d => d.ProductID, p => p.ProductID,
                (d, p) => new { detail = d, product = p });
    }
}