实体框架通过linq语法与子查询连接

时间:2014-05-29 12:16:28

标签: sql sql-server linq entity-framework linq-to-entities

我试图在linq sintax中翻译sql查询,但我遇到了大麻烦

这是我在SQL中的查询

select * FROM dbo.ITEM item  inner join 
(
    select SUM([QTA_PRIMARY]) QtaTotale,
    TRADE_NUM,
    ORDER_NUM,
    ITEM_NUM
    from [dbo].[LOTTI]
    where FLAG_ATTIVO=1
    group by [TRADE_NUM],[ORDER_NUM],[ITEM_NUM]
) 
TotQtaLottiGroupByToi

on item.TRADE_NUM = TotQtaLottiGroupByToi.TRADE_NUM
and item.ORDER_NUM = TotQtaLottiGroupByToi.ORDER_NUM
and item.ITEM_NUM = TotQtaLottiGroupByToi.ITEM_NUM
where item.PRIMARY_QTA > TotQtaLottiGroupByToi.QtaTotale

and item.FLAG_ATTIVO=1

我怎样才能翻译成linq sintax? 这种方法不起作用

var res= from i in context.ITEM
                    join d in 
                    (
                         from l in context.LOTTI
                         group l by new { l.TRADE_NUM, l.ORDER_NUM, l.ITEM_NUM } into g
                         select new TotQtaByTOI()
                         {
                            TradeNum = g.Key.TRADE_NUM,
                            OrderNum = g.Key.ORDER_NUM,
                            ItemNum = g.Key.ITEM_NUM,
                            QtaTotale = g.Sum(oi => oi.QTA_PRIMARY)

                        }
                     )
                  on new { i.TRADE_NUM, i.ORDER_NUM, i.ITEM_NUM} equals new { d.TradeNum, d.OrderNum, d.ItemNum }

我收到此错误

The type of one of the expressions in the join cluase is incorrect. Type inference failed in the call to 'Join'

你可以帮我解决这个问题吗? 谢谢!

1 个答案:

答案 0 :(得分:0)

问题是匿名类型比较。您需要为两个匿名类型的属性指定匹配的属性名称(例如,第一,第二,第三)

我试过了,这是一个例子:http://pastebin.com/hRj0CMzs