如何用LinQ写SQL?

时间:2009-06-19 12:25:50

标签: linq-to-sql

SELECT P.ProductId, P.ProductCategoryId, P.ParentProductCategoryId, 
       P.ProductName, PC.Name AS Category, P.Price, P.ProductYear
FROM   dbo.ProductCategory AS PC 
INNER JOIN
  (SELECT dbo.ProductCategory.ParentProductCategoryId, 
          dbo.ProductCategory.ProductCategoryId, 
          dbo.ProductCategory.Name AS CategoryName, 
          dbo.Product.ProductId, 
          dbo.Product.Price, 
          dbo.Product.Name AS ProductName, 
          dbo.Product.ProductYear
   FROM dbo.Product 
   INNER JOIN dbo.ProductCategory 
   ON dbo.ProductCategory.ProductCategoryId = dbo.Product.ProductCategoryId
  ) AS P 
ON PC.ProductCategoryId = P.ParentProductCategoryId

1 个答案:

答案 0 :(得分:1)

我不太确定您的数据库布局,但LINQ语句看起来像这样......

YourDataContext db = new YourDataContext();

var query =
    from p in db.Products
    join pc in db.ProductCategories on p.ProductCategoryId equals pc.ProductCategoryId 
    select new 
    {
        p.ProductId,
        p.ProductCategoryId,
        p.ParentProductCategoryId,
        p.ProductName,
        Category = pc.Name,
        p.Price,
        p.ProductYear 
    }