【问题标题】:ASP.NET MVC - Foreign Key / Parent-Child and editing recordsASP.NET MVC - 外键/父子和编辑记录
【发布时间】:2011-08-23 16:14:56
【问题描述】:

我有许多类与位置、货币等属性的其他类有关系。举个例子:

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 时,货币被正确报告为更改的货币,但数据库中交易记录上的货币 ID 未更新。

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

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

我很难过,如果有任何帮助,我将不胜感激!

【问题讨论】:

  • 只是在黑暗中的一个镜头...发布到编辑的交易的 ID 设置是否正确?
  • 是的。如果我更改交易的任何其他属性,如数量,它会正确保存

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


【解决方案1】:

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

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

【讨论】:

    猜你喜欢
    • 2010-10-17
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-06-21
    • 2019-11-13
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多