如何在LInq中使用两个或多个表进行左连接到Sql查询?

时间:2014-09-19 13:29:49

标签: c# sql linq linq-to-sql

我想在Linq to Sql查询中使用两个或多个表执行左连接,但看起来在C#中没有关键字。有没有办法以与使用Linq to Sql进行内部连接相同的方式执行左连接?

public IQueryable GetProducts(int productID)
{
    var products = 
        from p in this.Products 
        left join c in this.ProductCategoryProducts 
        on p.CategoryID equals c.ProductCategoryID
        left join ac in this.ProductCategories 
        on c.ProductCategoryID equals ac.ProductCategoryID
        where p.ProductID == productID
        select new
        {
            ProductID = a.ProductID,
            Heading = p.Heading,                
            Category = ac.ProductCategory
        };
    return products ;
}

2 个答案:

答案 0 :(得分:0)

public IQueryable GetProducts(int productID)
{
    var products = 
        from p in this.Products 
        join c in this.ProductCategoryProducts 
        on p.CategoryID equals c.ProductCategoryID into pclj
        from pc in pclj.DefaultIfEmpty()
        join ac in this.ProductCategories 
        on c.ProductCategoryID equals ac.ProductCategoryID into pcidlj
        from pcid in pcidlj.DefaultIfEmpty()
        where p.ProductID == productID
        select new
        {
            ProductID = p.ProductID,
            Heading = p.Heading,                
            Category = pcid != null ? pcid.ProductCategory : null
        };
    return products ;
}

答案 1 :(得分:0)

无论如何,我以这种方式使用Lambda表达式得到了解决方案:

var products = 
        from p in this.Products 
        join cat in this.ProductCategoryProducts 
        .Where(c => c.ProductID == p.ProductID).DefaultIfEmpty()

        from pc in this.ProductCategories 
        .Where(pc => pc.ProductCategoryID == cat.ProductCategoryID).DefaultIfEmpty()

        where p.ProductID == productID
        select new
        {
            ProductID = p.ProductID,
            Heading = p.Heading,                
            Category = pc.ProductCategory
        };
    return products ;