簡體   English   中英

ASP.NET MVC-外鍵/父子項和編輯記錄

[英]ASP.NET MVC - Foreign Key / Parent-Child and editing records

我有許多類,它們與諸如Location,Currency等屬性的其他類有關系。以下面的示例為例:

Public Class Transaction
     Public Property ID As Integer
     Public Property Description As String
     Public Property Quantity As Integer
     Public Property SaleAmount As Double
     Public Overridable Property Currency As Currency
 End Class

 Public Class Currency
     Public Property ID As String
     Public Property Description As String
     Public Property Symbol As String
     Public Property SymbolImage As String
 End Class

初始化首次使用的應用程序時,我會添加貨幣。 添加交易時,我有一個下拉框來選擇貨幣。 我將事務保存到數據庫沒有問題,貨幣ID也保存了。

當我編輯交易並嘗試更改貨幣時,我無法將其保存回數據庫。

 <HttpPost()>
    Function Edit(transaction As Transaction) As ActionResult
        transaction.Currency = db.Currencies.Find(transaction.Currency.ID)
        Debug.Print("Currency: " & transaction.Currency.ID)
        If ModelState.IsValid Then
            db.Entry(transaction).State = EntityState.Modified
            db.SaveChanges()
            Return RedirectToAction("Index")
        End If

        Return View(transaction)
    End Function

當我在上述post方法中執行debug.print時,貨幣已正確報告為更改后的貨幣,但數據庫中Transaction記錄上的Currency ID並未更新。

我已經做了一些搜索和閱讀,卻沒有發現太多/任何東西。 我確實嘗試將這一行添加到post方法中,但是它仍然沒有保存更改:

db.Entry(transaction.Currency).State = EntityState.Modified

我很沮喪,不勝感激!

因此,這是我能找到的最佳解決方案。 我很想聽聽其他獲得相同結果的方法。 我發現的其他方法比這復雜得多。

Public Class Transaction
    Public Property ID As Integer
    Public Property Description As String
    Public Property Quantity As Integer
    Public Property SaleAmount As Double
    Public Property Name As String

    Public Property CurrencyID() As String
    <ForeignKey("CurrencyID")>
    Public Overridable Property Currency() As Currency
End Class

我用一個下拉列表設置了Edit視圖,該下拉列表包含貨幣列表和一個用於存儲CurrencyID的隱藏字段。 編輯帖子如下所示:

<HttpPost()>
Function Edit(transaction As Transaction) As ActionResult
    If ModelState.IsValid Then
        db.Entry(transaction).State = EntityState.Modified
        db.SaveChanges()
        Return RedirectToAction("Index")
    End If

    Return View(transaction)
End Function

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM