复杂的实体框架查询

时间:2013-10-02 20:35:35

标签: vb.net entity-framework

我正在努力解决复杂的EF查询

查询传递一个整数,它定义了回顾股票收盘价的天数,以确定最近的每一天是否低于先前(即查看每一天的价格是否低于回顾我正在努力研究如何纳入价格测试。我可以检索必需的天数,但不确定我是否可以在一个查询中完成整个过程,或者是否应将其拆分为另一个查询以获得结果。任何帮助赞赏。 (AddBusinessDays是我自己的仅使用businessdays的功能)

 Public Shared Function GetDailyEquityDownMoves(ByVal numdaysback As Int32) As List(Of String)
    Dim qualifiedDownStocks As New List(Of String)
    Using ctx As New QE2DatabaseEntities()
        Dim symblist As List(Of Int64) = (From sym In ctx.symbols Select sym.idsymbols).ToList()
        For Each symId As Int64 In symblist
            Dim query = (From q In ctx.pricedatas
                             Where q.symid = symId
                             Join d In ctx.symbols On d.idsymbols Equals symId
                             Where q.pricedate < DateTime.Now AndAlso q.pricedate > AddBusinessDays(DateTime.Now.AddDays(numdaysback * -1))
                             Order By q.pricedate Ascending
                             Select q.closeprice).ToList()
            'Now test to see if each closeprice is less than the prior starting with most recent date
            'if it qualifies add it to the list
            'qualifiedDownStocks.Add(result)

        Next



    End Using
End Function

1 个答案:

答案 0 :(得分:0)

你真的应该有Option Strict On。既然不是,我不得不猜测数据类型,因为你没有强烈地输入你的查询。此外,您没有准确说明要添加到列表中的内容,因此我猜到了symId。如果我的猜测是错误的,请更改该部分。无论如何,看看这样的东西是否有效:

Public Shared Function GetDailyEquityDownMoves(ByVal numdaysback As Int32) As List(Of String)
    Dim qualifiedDownStocks As New List(Of String)
    Using ctx As New QE2DatabaseEntities()
        Dim symblist As List(Of Int64) = ctx.symbols.ToList        

        For Each symId As Int64 In symblist
            Dim previousPrice As Integer = 0
            Dim query As IEnumerable (Of pricedata) = (From q In ctx.pricedatas
                                                       Where q.symid = symId
                                                       Join d In ctx.symbols On d.idsymbols Equals symId
                                                       Where q.pricedate < DateTime.Now  AndAlso q.pricedate > AddBusinessDays(DateTime.Now.AddDays(numdaysback * -1))
                                                       Order By q.pricedate Ascending
                                                       Select q)

            'Now test to see if each closeprice is less than the prior starting with most recent date
            For Each closing As pricedata In query
                Dim closingPrice As Decimal = closing.closeprice
                'if it qualifies add it to the list
                If closingPrice < previousPrice Then
                    qualifiedDownStocks.Add(closing.symId & vbTab & closing.pricedate)
                End If
                previousPrice = closingPrice
            Next

        Next       

    End Using
End Function

你可以用LINQ完成整个过程,但是我离开了For Each循环,因为它使整个事情比一个巨大的LINQ语句更容易理解。