1

尝试运行以下 LINQ 语句:

Dim jobId As Integer = CInt(payment.ForJob)

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

在 a.Amount 上得到以下错误:范围变量“金额”隐藏封闭块中的变量或先前在查询表达式中定义的范围变量

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
4

1 回答 1

4

我怀疑这是问题所在:

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

我不太了解VB,但我怀疑这个变量的范围是整个块的范围,包括那个LINQ语句。至少在 C# 中,这不是问题……但Select我相信 VB 中的子句的工作方式有所不同。

一种替代方法是直接计算总和:

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

我的VB很差,但我认为应该可以。

于 2012-09-28T08:57:57.530 回答