Click here to Skip to main content
15,895,011 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
I had an MVC application to update a table in a database, but now I needed to add a ViewModel so that I could have the multiple tables displaying on a view page. But the problem now is that it will not save into the database now. I am using database first approach (not code-first).

Here is what I have so far:

In my ViewModel:
VB
Public Class ClientUserProjectIssue
    Public Property uTable As UserTable
    Public Property issueType As IssueTypeTable
    Public Property IssueTable As IssueTable
End Class

In the view:
VB
@ModelType IssueTracker.ClientUserProjectIssue

@Html.EditorFor(Function(model) model.IssueTable.IssueSummary)
@Html.EditorFor(Function(model) model.IssueTable.IssueDescription)

In my controller:
VB
Public Function UpdateIssue(issue As IssueTracker.ClientUserProjectIssue, objModelMail As IssueTable, command As String) As ActionResult

dbServer.Entry(issue).State = EntityState.Modified
dbServer.SaveChanges()

I will now get a null value because I am using the ViewModel instead of a single table.
I was trying to implement something like this:
VB
Using context As New DbContext()
    Dim dataModel As DatabaseEntities= context.IssueEntiteis.where(Function(x) x.Id = viewModel.Id).First()
    dataModel.Name = viewModel.Name
    dataModel.Type = viewModel.Type
    context.SaveChanges()
End Using

But I was getting errors so I am pretty sure I can't do it that way because I am using database first, how can I implement a viewModel so that I can save tables in a database?
Posted
Comments
Richard Deeming 4-Aug-15 8:49am    
Did you try using the viewmodel as the parameter to the update method?

Public Function UpdateIssue(viewModel As ClientUserProjectIssue) As ActionResult
Ciaran82 4-Aug-15 9:32am    
Yes I have it nearly working the problem was dbServer.Entry(issue).State = EntityState.Modified was incorrect but I changed it to issue.IssueTable but now I get the error "Store update, insert, or delete statement affected an unexpected number of rows (0). Entities may have been modified or deleted since entities were loaded"

1 solution

I've run into this before. I found that I hadn't actually made any changes to the data. My solution was to create a temporary variable and update as follows:

VB
Using context As New DbContext()
    Dim dataModel As DatabaseEntities= context.IssueEntiteis.where(Function(x) x.Id = viewModel.Id).First()
    dataModel.Name = viewModel.Name
    dataModel.Type = viewModel.Type
    context.IssueEntiteis.AddOrUpdate(dataModel)
    context.SaveChanges()
End Using
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900