ASP.NET MVC - 外键/父子和编辑记录

时间:2011-08-23 16:14:57

标签: asp.net-mvc vb.net asp.net-mvc-3 model-view-controller

我有很多类与其他类有关系,比如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时,货币被正确报告为已更改的货币,但DB中的交易记录上的货币ID未更新。

我做了一些搜索和阅读,并没有发现太多/任何东西。 我确实尝试将此行添加到post方法,但它仍然没有保存更改:

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

我很难过,希望得到任何帮助!

1 个答案:

答案 0 :(得分:0)

所以这是我能找到的最佳解决方案。我有兴趣听到其他方法来实现相同的结果。我发现的其他方法要比这复杂得多。

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

我设置了编辑视图,其中包含一个包含货币列表的下拉列表和一个用于存储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