所以,我在翻译为 LINQ(并且工作 - 经过测试)的 SQL 查询时遇到了问题,但相同的 LINQ 查询在 Lightswitch 中不起作用。当然,我没想到会直接工作,但我正在努力正确转换它。
因此,这是我查询所基于的表的图像:
http://dl.dropbox.com/u/46287356/tables.PNG
(抱歉外部链接,但没有足够的代表积分:))
SQL 查询如下所示:
SELECT WorkingUnits.Name AS WUName, ContractPositions.WUInstanceId,
Materials.Cost, BillingValues.Value, BillingValues.PricePerUnit
FROM WorkingUnits
INNER JOIN
Materials ON WorkingUnits.Id = Materials.Material_WorkingUnit
INNER JOIN ContractPositions ON
Materials.Id = ContractPositions.ContractPosition_Material
INNER JOIN BillingValues ON
ContractPositions.Id = BillingValues.BillingValue_ContractPosition
现在,我已通过以下方式将其转换为 LINQ:
var query = from wu in this.DataWorkspace.ApplicationData.WorkingUnits
join m in this.DataWorkspace.ApplicationData.Materials on
new { Id = WorkingUnits.Id } equals new { Id = m.Material_WorkingUnit }
join cp in this.DataWorkspace.ApplicationData.ContractPositions on
new { Id = m.Id } equals new { Id = cp.ContractPosition_Material }
join bv in this.DataWorkspace.ApplicationData.BillingValues on
new { Id = cp.Id } equals new { Id = bv.BillingValue_ContractPosition }
select new
{
usage = bv.Value * bv.PricePerUnit,
totalCost = (bv.Value * bv.PricePerUnit) * m.Cost,
amount = (bv.Value*bv.PricePerUnit) * m.Cost / wu.WUPrice
};
请注意,我已经更改了一些内容 - 例如列的部分,因为我在Lightswitch中不需要它。
因此,虽然这再次适用于SQL服务器,但Lightswitch抱怨我必须考虑明确指定范围变量"WorkingUnits"的类型。我试图铸造它,但随后还有其他错误,例如:
'int' does not contain a definition for 'Id' and no extension method 'Id'
accepting a first argument of type 'int' could be found (are you missing
a using directive or an assembly reference?)
所以我的问题是,如何正确转换该查询并期望它工作?另外,如果我们认为我的数据库设置正确,我甚至需要在 LINQ 中使用"联接"吗?任何想法都值得赞赏!
尝试这样的事情
var query = from wu in this.DataWorkspace.ApplicationData.WorkingUnits
join m in this.DataWorkspace.ApplicationData.Materials on
wu.Id equals m.WorkingUnitID }
join cp in this.DataWorkspace.ApplicationData.ContractPositions on
m.Id equals cp.ContractPosition_Material
join bv in this.DataWorkspace.ApplicationData.BillingValues on
cp.Id equals bv.BillingValue_ContractPosition
select new
{
usage = bv.Value * bv.PricePerUnit,
totalCost = (bv.Value * bv.PricePerUnit) * m.Cost,
amount = (bv.Value*bv.PricePerUnit) * m.Cost / wu.WUPrice
};
从底部(计费值)开始并使用实体引用逐步向上呢?
例如
var query = from bv in this.DataWorkspace.ApplicationData.BillingValues
let m = bv.ContractPosition.Material
let wu = m.WorkingUnit
select new
{
usage = bv.Value * bv.PricePerUnit,
totalCost = (bv.Value * bv.PricePerUnit) * m.Cost,
amount = (bv.Value*bv.PricePerUnit) * m.Cost / wu.WUPrice
};