I’ve got a number of classes which have a relationship to other classes for properties like Location, Currency etc. Take the following example:
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
I add my currencies when I initialise the application for first use. When adding a transaction, I have a drop down box to select the currency.
I have no issues saving the Transaction to the db and the currency ID is saved also.
When I edit the transaction and try to change the currency, I can’t get it to save back to the db.
<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
When I do the debug.print in the post method above, the currency is correctly being reported as the changed currency but the Currency ID on the Transaction record in the DB isn’t updated.
I’ve done some searching and reading and haven’t found much/anything.
I did try adding this line to the post method but it still didn’t save the changes:
db.Entry(transaction.Currency).State = EntityState.Modified
I’m stumped and would appreciate any help!
So here’s the best solution I could find. I’d be interested to hear other ways to achieve the same result. The other methods I’ve found are much more complicated than this.
I’ve setup the Edit view with a drop down list containing a list of the currencies and a hidden field to store the CurrencyID. The edit post looks like this: