我一直在處理這個問題至少兩天了。我沒有一本可供參考的書,而且我不能在我的生活中找到解釋該如何工作的解釋。在實體框架/ ASP.NET MVC中保存具有關係的實體2
我所試圖做的是一個簡單的操作:
- 加載一個創建表格填入3下拉列表元素,其引用其他表
- 填寫表格
- 提交表單和保存實體
我已經盡了各種方式來想辦法讓這個工作。這應該很容易。我曾嘗試過,沒有ViewModel。我認爲它沒有ViewModel更清晰
注意:由於要求,我使用.NET 3.5。這是否意味着我在EF的舊版本上?
另一個注意:是的,我使用VB。不,那不是我的選擇。
控制器:
Function Create() As ActionResult
PopulateForm()
Return View()
End Function
<HttpPost()>
Function Create(ByVal escalation As Escalation) As ActionResult
If TryUpdateModel(escalation) Then
repo.AddEscalation(escalation)
repo.Save()
Return RedirectToAction("Details", New With {.Id = escalation.Id})
End If
'The model did not save - there are validation errors'
PopulateForm()
Return View()
End Function
Private Sub PopulateForm()
ViewData("categoryList") = repo.GetAllCategories().ToList()
ViewData("statusList") = repo.GetAllStatuses().ToList()
ViewData("pathList") = New List(Of Path)
End Sub
庫:
Public Sub AddEscalation(ByVal esc As Escalation)
esc.Created_At = DateTime.Now()
entities.AddToEscalations(esc)
End Sub
Public Sub Save()
entities.SaveChanges()
End Sub
查看:
<div class="editor-label">
<%= Html.LabelFor(Function(model) model.Status)%>
</div>
<div class="editor-field">
<%= Html.DropDownListFor(Function(model) model.Status, New SelectList(ViewData("statusList"), "Id", "Name"))%>
<%= Html.ValidationMessageFor(Function(model) model.Status)%>
</div>
<div class="editor-label">
<%= Html.LabelFor(Function(model) model.Category)%>
</div>
<div class="editor-field">
<%= Html.DropDownListFor(Function(model) model.Category, New SelectList(ViewData("categoryList"), "Id", "Name"))%>
<%= Html.ValidationMessageFor(Function(model) model.Category)%>
</div>
當使用DropDownListFor ... model.Property,它在TryUpdateModel調用失敗。驗證錯誤在返回的表單中看起來像這樣:值'35'無效。
如果我將其更改爲DropDownListFor ... model.Property.Id,它死在調用SaveChanges()像這樣:
Cannot insert the value NULL into column 'Name',
table 'Escalations_Dev.dbo.Categories';
column does not allow nulls. INSERT fails.
The statement has been terminated.
在調試時,我的升級確實有一個類別,只有編號財產填充和分離狀態。
如果我做了以下填充完整的對象:
Public Sub AddEscalation(ByRef esc As Escalation)
esc.Created_At = DateTime.Now()
esc.Category = Me.GetCategory(esc.Category.Id)
esc.Status = Me.GetStatus(esc.Status.Id)
esc.Path = Me.GetPath(esc.Path.Id)
entities.AddToEscalations(esc)
End Sub
Public Function GetPath(ByVal id As Integer) As Path
Dim path As Path = entities.Paths.FirstOrDefault(Function(c) c.Id = id)
path.CategoryReference.Load()
Return path
End Function
我得到:在「Escalations_Conn.Paths」實體參加「FK_Paths_Categories」的關係。找到0個相關的「分類」。 1'類別'預計。
我真的很感謝任何人的幫助。
好的,那麼你得到的錯誤/結果是什麼? – 2010-09-29 15:54:09
對不起,我在底部添加了更多關於結果的詳細信息。 – ItsJason 2010-09-29 16:08:39