[英]Linq. Select from multiple tables
在项目中我有这个表:
还有Product
型号(id, name, catalogId, catalogTitle, manufacturerId, manufacturerName)
。
如果我想获得Product项,如何在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
首先,我会回答你的问题..然后解决你的评论答案。 要回答您的问题,请在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 };
这将使您的查询结果引用更少痛苦。
要回答你的评论,如果你想要的只是产品,你就会做很多连接。 您的标准只能确保三件事
如果#2和#3是多余的,并且您不一定需要这些名称,您可以简单地执行以下操作:
from p in Product
where p.Active == 1
select p
如果Product是CRUD模型,您可以深度加载它以包含制造商/目录信息,或使用上述视图模型。
祝好运!
要合并多个表的结果而不显式连接:
from p in Product
from c in Catalog
from m in Manufacturer
where c.Id == p.CatalogId && m.Id == p.ManufacturerId && p.Active == 1
select new
{
p.Name,
p.CatalogId,
p.ManufacturerId,
c.Name,
m.Name
};
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.