2012-09-09 68 views
12

在项目选择我有这个表:Linq。从多个表

  1. 产品(ID,采用catalogId,manufacturerId ...)
  2. 目录
  3. 厂商

而且Product模型(id, name, catalogId, catalogTitle, manufacturerId, manufacturerName)

如果我想获得产品项目,如何在Linq中写下这个SQL查询?

SELECT Product.Name, Product.CatalogId, Product.ManufacturerId, [Catalog].Name, Manufacturer.Name 
FROM Product, [Catalog], Manufacturer 
WHERE [Catalog].Id=Product.CatalogId AND Manufacturer.id=Product.ManufacturerId AND Product.Active=1 
+1

发生了什么事情加入? http://www.dotnetperls.com/join – TigOldBitties

+0

@TigOldBitties我最近编辑了我的问题。我想获得产品项目。 –

+0

无论你想要得到什么,该问题仍然适用。 – TigOldBitties

回答

40

首先,我会回答你的问题,然后解答你对问题的回答。要回答你的问题,Linq中你会做到以下几点:

from p in Product 
join c in Catalog on c.Id equals p.CatalogId 
join m in Manufacturer on m.Id equals p.ManufacturerId 
where p.Active == 1 
select new { Name = p.Name, CatalogId = p.CatalogId, ManufacturerId = p.ManufacturerId, CatalogName = c.Name, ManufacturerName = m.Name }; 

这会给你和你所要求的项目一个匿名对象。如果你需要在别处使用它(并且你没有使用动态对象),我会建议创建一个视图模型,并在你的选择中实例化其中的一个。

例子:

public class ProductInfoView 
{ 
    public string Name { get; set; } 
    public int CatalogId { get; set; } 
    public int ManufacturerId { get; set; } 
    public string CatalogName { get; set; } 
    public string ManufacturerName { get; set; } 
} 


from p in Product 
join c in Catalog on c.Id equals p.CatalogId 
join m in Manufacturer on m.Id equals p.ManufacturerId 
where p.Active == 1 
select new ProductInfoView() { Name = p.Name, CatalogId = p.CatalogId, ManufacturerId = p.ManufacturerId, CatalogName = c.Name, ManufacturerName = m.Name }; 

这将使引用查询结果少一点痛苦。

要回答你的评论,你要做的很多连接,如果你想要的只是产品。您的标准只能保证三件事

  1. 你的产品的活动标志是1
  2. 你的产品有一个现有的目录条目
  3. 你的产品有一个现有的制造商进入

如果#2和# 3是多余的,你不一定需要名称,你可以简单地做:

from p in Product 
where p.Active == 1 
select p 

如果产品是CRUD模型,则可以将其深度加载以包含制造商/产品目录信息或使用上述视图模型。

祝你好运!