如何使用ViewModel数据库优先方法在数据库中保存表? [英] How do I save a table in a database using a ViewModel database-first approach?
问题描述
我有一个MVC应用程序来更新数据库中的表,但现在我需要添加一个ViewModel,以便我可以在视图页面上显示多个表。但现在的问题是它现在不会保存到数据库中。我正在使用数据库第一种方法(不是代码优先)。
这是我到目前为止:
在我的ViewModel中:
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:
Public Class ClientUserProjectIssue
Public Property uTable As UserTable
Public Property issueType As IssueTypeTable
Public Property IssueTable As IssueTable
End Class
在视图中:
In the view:
@ModelType IssueTracker.ClientUserProjectIssue
@Html.EditorFor(Function(model) model.IssueTable.IssueSummary)
@Html.EditorFor(Function(model) model.IssueTable.IssueDescription)
在我的控制器中:
In my controller:
Public Function UpdateIssue(issue As IssueTracker.ClientUserProjectIssue, objModelMail As IssueTable, command As String) As ActionResult
dbServer.Entry(issue).State = EntityState.Modified
dbServer.SaveChanges()
我现在将得到一个空值,因为我使用的是ViewModel而不是单表。
我试图实现这样的事情:
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:
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
但我是得到错误所以我很确定我不能这样做,因为我首先使用数据库,我如何实现一个viewModel,以便我可以在数据库中保存表?
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?
推荐答案
之前我遇到过这个问题。我发现我实际上没有对数据进行任何更改。我的解决方案是创建一个临时变量并更新如下:
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:
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
这篇关于如何使用ViewModel数据库优先方法在数据库中保存表?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!