LINQ Group By(VB.net& Linq to Entities)

时间:2015-05-04 23:45:23

标签: vb.net linq

我正试图让一群人去Linq工作:

from document in Documents
  Group Join documentInstrument In DocumentInstruments
      On document.DocumentId Equals documentInstrument.DocumentId
      Into relatedDocumentInstruments = Group
      From documentInstrument In relatedDocumentInstruments.DefaultIfEmpty()
  Group Join instrument In Instruments
      On documentInstrument.InstrumentId Equals instrument.InstrumentId
      Into relatedInstruments = Group
      From instrument In relatedInstruments.DefaultIfEmpty()
  where (document.DocumentId = 1294201 Or document.DocumentId = 1294179)
  Order by instrument.Name
  Select New With
  {
    .Code = instrument.Code,
    .InstrumentName = instrument.Name
  }

这基本上留给我重复(相同的代码和名称)。我已经尝试了几乎每一个" Group By"语法我可以通过谷歌找到,似乎没有任何工作。

以下是我尝试转换为Linq(对于实体)的原始查询:

Sql = "SELECT Instruments.Name AS Instrument, Instruments.Code, COUNT(Instruments.Name) AS InstrumentCount, " & _
"SUM(Documents.Pages) AS TotalPages, SUM(Fees.FeeAmount) AS FeeAmount " & _
"FROM Documents LEFT JOIN DocInstruments ON Documents.DocID = DocInstruments.DocID AND DocInstruments.IsPrimary = <TRUE /> " & _
"LEFT JOIN Instruments ON DocInstruments.InstrumentID = Instruments.InstrumentID " & _
"LEFT JOIN (SELECT DocumentID, SUM(Amount) AS FeeAmount FROM Transactions WHERE PaymentType = 'Charge' and Void = <FALSE /> " & _
"GROUP BY DocumentID) AS Fees ON Documents.DocID = Fees.DocumentID " & _
"WHERE Documents.DocID IN (" & sList & ") " & sInstWhere & _
"GROUP BY Instruments.Name, Instruments.Code " & _
"ORDER BY Instrument"

**我暂时从我的linq查询中将联接留给了Transactions表,只是在添加更多**之前尝试让代码/名称正常工作

编辑:

好的,如果我能弄清楚如何将以下查询转换为linq,那将是一个良好的开端。我似乎无法通过......来加入小组。

SELECT i.Code, i.Name
from Instruments i
LEFT JOIN DocInstruments di on i.InstrumentId = di.InstrumentId
group by i.Code, i.Name
order by i.Code

似乎不应该那么难,而且一旦你知道语法就可能没有了,但是我无法让任何事情发挥作用而且Linqer无法连接到我的EF版本。长号。

那里有哪些linq专家可以提供帮助?

1 个答案:

答案 0 :(得分:0)

在将大量直接SQL查询转换为LINQ后,我想我终于想出了分组。所以在我上面的问题中:

SELECT i.Code, i.Name
from Instruments i
LEFT JOIN DocInstruments di on i.InstrumentId = di.InstrumentId
group by i.Code, i.Name
order by i.Code

会是这样的(只是在这里输入,而不检查,但这应该是关闭的):

(FROM instrumentEntity in dbContext.InstrumentEntities
GROUP Join documentInstrumentEntity
    ON instrumentEntity.InstrumentId equals documentInstrumentEntity.InstrumentId Into foundDocumentInstruments = Group
    FROM foundDocumentInstrument in foundDocumentInstruments.DefaultIfEmpty()
SELECT NEW With 
{
.Code = instrumentEntity.Code,
.Name = instrumentEntity.Name
}).GroupBy(Function(result) New With 
    {
    Key result.Code,
    Key result.Name
    }).ToList()

使用VB.Net时,如果您使用超过1个属性进行分组,则使用&#34; Key&#34;非常重要。每个字段上的标识符,否则分组将不起作用。

相关问题