SQL 到 Linq 实体
Posted
技术标签:
【中文标题】SQL 到 Linq 实体【英文标题】:SQL to Linq-Entities 【发布时间】:2013-09-10 07:42:12 【问题描述】:请帮我在 LINQ-Enitites 中转换这个 SQL 查询
select e.RowMeterialName,f.RowUnitName,*,isnull((b.Quantity - (Select SUM(a.Quantity) from PurchaseDetail a
join PurchaseMaster c on a.PurchaseId=c.PurchaseId
where a.RawMetId=b.RawMetrialId and c.PurchaseOrderId=b.PurchaseOrderId)),b.Quantity) as Remain
from PurchaseOrderDetail b
join RawMeterialMaster e on b.RawMetrialId=e.RawMetId
join RawUnitMaster f on e.RawUnitId=f.RowUnitId
where b.PurchaseOrderId=@PurchaseOrderId
请帮帮我。
【问题讨论】:
请不要只删除 SQL 并要求转换。至少显示一个类模型,以便导航属性和关联的多样性是可见的。 SO 在粘贴图像之前要求 10 个回购点。 【参考方案1】:这是一个长镜头,但你可以试试:
PurchaseDetail
.Join
(
PurchaseMaster,
x=>x.PurchaseId,
x=>x.PurchaseId,
(detail,master)=>new detail,master
)
.Join
(
PurchaseOrderMaster,
x=>x.PurchaseOrderId,
x=>x.PurchaseOrderId,
(joined,ordermaster)=>newdetail=joined.detail,master=joined.master,ordermaster
)
.Select
(
x=>
newdetail.Quantity,detail.RawMetId
)
.GroupBy(x=>x.RawMetId)
.Select
(
x=>
new
RawMetId=x.Key,
Quantity=x.Sum(z=>z.Quantity)
)
.Join
(
PurchaseOrderDetail,
x=>x.RawMetrialId,
x=>x.RawMetId,
(subquery,orderdetail)=>newsubquery,Remain=subquery.Quantity - orderdetail.Quantity
)
【讨论】:
【参考方案2】:谢谢大家,但我找到了这个查询的结果
from b in db.PurchaseOrderDetails
select new
b.RawMeterialMaster.RowMeterialName,
PurOrderDetailId = b.PurOrderDetailId,
PurchaseOrderId = b.PurchaseOrderId,
RawMetrialId = b.RawMetrialId,
DueOn = b.DueOn,
Quantity = b.Quantity,
ItemRate = b.ItemRate,
MetrialUnitsId = b.MetrialUnitsId,
Remark = b.Remark,
RowUnitName = b.RawMeterialMaster.RawUnitMaster.RowUnitName,
ReOrderQuantity = (decimal?)b.RawMeterialMaster.ReOrderQuantity,
Remain = ((System.Decimal?)b.Quantity -
(from a in db.PurchaseDetails
where
a.RawMetId == b.RawMetrialId &&
a.PurchaseMaster.PurchaseOrderId == b.PurchaseOrderId
select new
a.Quantity
).Sum(p => p.Quantity) ?? (System.Decimal?)b.Quantity)
;
【讨论】:
如果有人想将 SQL 转换为 LinQ,请使用第三方工具 Linqer 和 LinqPad。这些非常有用。感谢陈快乐。以上是关于SQL 到 Linq 实体的主要内容,如果未能解决你的问题,请参考以下文章
在运行时将实体对象添加到 LINQ-to-SQL 数据上下文 - SQL、C#(WPF)