我很難在傳入我的控制器之後獲取嵌套集合(標籤在我的情況下)以提交回數據庫。我正在使用EF 4.1和DbContext API,MVC 3和Automapper。使用MVC 3,EF 4.1,DbContext和AutoMapper保存嵌套集合
我的模型:
Partial Public Class Proposal
Public Property Id As Integer
Public Property Memo As String
Public Property EntryDate As Nullable(Of Date)
Public Overridable Property CategoryTags As ICollection(Of CategoryTag) = New HashSet(Of CategoryTag)
End Class
Public Class ProposalViewModel
Public Property Id As Integer
<DataType(DataType.MultilineText)>
Public Property Memo As String
<DisplayFormat(ApplyFormatInEditMode:=True, DataFormatString:="{0:d}")>
Public Property EntryDate As Nullable(Of Date)
Public Overridable Property CategoryTags As ICollection(Of CategoryTag) = New HashSet(Of CategoryTag)
End Class
我的看法使用代碼從下面的帖子添加標籤:http://jarrettmeyer.com/post/2995732471/nested-collection-models-in-asp-net-mvc-3。基本上這些標籤是通過添加INPUT元素並將其名稱屬性設置爲「CategoryTag [0] .Id」,「CategoryTag [1] .Id」等等來創建的,這些輸入的值是我數據庫中標籤的有效ID
最後,我郵編:
<HttpPost()>
Public Function Edit(ByVal pvm As ProposalViewModel) As ActionResult
Dim p As New Proposal
p = AutoMapper.Mapper.Map(Of ProposalViewModel, Proposal)(pvm)
If (ModelState.IsValid) Then
db.Entry(p).State = EntityState.Modified
db.SaveChanges()
Return RedirectToAction("Index")
Else
Return View(pvm)
End If
End Function
的PVM對象返回到我的設定值控制器我希望他們是。如果我在運行時添加了兩個標籤,那麼它的集合中有兩個CategoryTag對象,並帶有相應的ID。問題是,在我調用SaveChanges時,相應的記錄不會在我的多對多關係表(本例中爲ProposalCategoryTag)中創建。
任何想法我做錯了什麼?
UPDATE:
我沒有找到這樣的東西,並紛紛使出做手工像下面。我不喜歡這種方法,但它的工作原理。
<HttpPost()>
Public Function Edit(ByVal pvm As ProposalViewModel) As ActionResult
Dim p As New Proposal
Dim tempTag As CategoryTag
p = AutoMapper.Mapper.Map(Of ProposalViewModel, Proposal)(pvm)
If (ModelState.IsValid) Then
db.Proposals.Attach(p)
db.Entry(p).Collection("CategoryTags").Load()
For Each ct As CategoryTag In pvm.Tags
tempTag = db.CategoryTags.Find(ct.Id)
If tempTag Is Nothing Then
Continue For
End If
If p.CategoryTags.Contains(tempTag) Then
Continue For
End If
p.CategoryTags.Add(tempTag)
Next
db.Entry(p).State = EntityState.Modified
db.SaveChanges()
Return RedirectToAction("Index")
Else
Return View(pvm)
End If
End Function
如果您想要回復,請將問題保留3天以上,這可能會有幫助。 – Karelzarath 2011-05-03 20:03:11