【发布时间】:2017-07-31 11:30:11
【问题描述】:
SELECT Meter.SerialNumber as serial,
SupplyPoint.Id as supplypoint,
SupplyType.Id as supplytype,
SupplyType.Name as supplytypename
FROM Meter
INNER JOIN SupplyPoint ON Meter.SupplyPointId = SupplyPoint.Id
INNER JOIN SupplyType ON SupplyPoint.SupplyTypeId = SupplyType.Id;
我有这个查询,以便我可以根据其序列号找到仪表的供应类型。到目前为止,我已经编写了这个函数:
var query = from meters in db.Meters
join supplyPoint in db.SupplyPoints on meters.SupplyPointId
equals supplyPoint.Id
join supplyType in db.SupplyTypes on supplyPoint.SupplyTypeId equals
supplyType.Id
select new { serial = meters.SerialNumber, type = supplyType.Name };
foreach (var meter in query)
{
if (meter.serial == serial)
return meter.type;
}
return "Meter Type Not Specified";`
所以我调用 FindType(string serial) 并返回类型。谁能建议更好的代码来转换这样的查询?也欢迎任何有关在何处了解有关 LINQ 的更多信息的说明。
【问题讨论】:
-
到目前为止你尝试过什么?你的数据库表是什么样的?您是否使用实体框架设置了数据上下文?
-
您的转换看起来不错,但通常您也会使用 LINQ 来找到答案:
var ans = (from meter in query where meter.serial == serial select meter).SingleOrDefault(); return (meter == null) ? "Meter Type Not Specified" : meter.type;
标签: c# sql visual-studio linq