NickP
NickP

Reputation: 1414

Error on LINQ statement with enclosing variable

Trying to run the following LINQ statment:

Dim jobId As Integer = CInt(payment.ForJob)

Dim currentPaid = From a In db.Payments
                      Where a.ForJob = jobId
                      Select a.Amount

Get the following error on a.Amount though: Range variable 'Amount' hides a variable in an enclosing block or a range variable previously defined in the query expression

Function RecordPaymentForJob(payment As Payment) As ActionResult
        If ModelState.IsValid Then

            Dim jobId As Integer = CInt(payment.ForJob)

            Dim new currentPaid = From a In db.Payments
                      Where a.ForJob = jobId
                      Select a.Amount

            Dim totalPaid As Double = currentPaid.Sum()

            If (totalPaid + payment.Amount) > (db.Jobs.Find(payment.ForJob).JobAmount * -1) Then
                db.Jobs.Find(payment.ForJob).JobStatus = "Paid"
            Else
                db.Jobs.Find(payment.ForJob).JobStatus = "Part Paid"
            End If

            Dim Id As Integer = payment.CustomerId
            Dim amount As Double = db.Customers.Find(Id).AccBalance
            amount += payment.Amount
            db.Customers.Find(Id).AccBalance = amount
            db.Payments.Add(payment)
            db.SaveChanges()
            Return Redirect("/Payment/PaymentSuccessful")
        End If

        Return View(payment)
    End Function

Upvotes: 1

Views: 1305

Answers (1)

Jon Skeet
Jon Skeet

Reputation: 1500515

I suspect this is the problem:

Dim amount As Double = db.Customers.Find(Id).AccBalance

I don't know VB very well, but I suspect the scope of this variable is the scope of the whole block, including that LINQ statement. In C# at least, that wouldn't be a problem... but the Select clause in VB works somewhat differently, I believe.

One alternative would be to compute the sum directly:

Dim totalPaid = db.Payments.Where(Function(a) a.ForJob = jobId).
                            Sum(Function(a) a.Amount)

My VB is pretty poor, but I think that should work.

Upvotes: 4

Related Questions