Ale*_*ack 15 c# sql linq select
在项目中我有这个表:
还有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
Run Code Online (Sandbox Code Playgroud)
Jai*_*res 45
首先,我会回答你的问题..然后解决你的评论答案.要回答您的问题,请在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 };
Run Code Online (Sandbox Code Playgroud)
这将为您提供一个包含您请求的项目的匿名对象.如果您需要在其他地方使用它(并且您没有使用动态对象),我建议您创建一个视图模型,并在您的选择中实例化其中一个.
例:
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 };
Run Code Online (Sandbox Code Playgroud)
这将使您的查询结果引用更少痛苦.
要回答你的评论,如果你想要的只是产品,你就会做很多连接.您的标准只能确保三件事
如果#2和#3是多余的,并且您不一定需要这些名称,您可以简单地执行以下操作:
from p in Product
where p.Active == 1
select p
Run Code Online (Sandbox Code Playgroud)
如果Product是CRUD模型,您可以深度加载它以包含制造商/目录信息,或使用上述视图模型.
祝好运!
小智 5
要合并多个表的结果而不显式连接:
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
};
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
69299 次 |
| 最近记录: |