我很难得到一个嵌套的集合(标签在我的情况下)被传递到我的控制器后提交回数据库。我使用EF 4.1与DbContext API, MVC 3和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元素并将其name属性设置为"CategoryTag[0]"来创建标记。Id"、"CategoryTag[1]。Id"等等……并且这些输入的值是我的数据库中标签的有效id
最后,我的POST代码:<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对象返回到我的控制器,其值设置为我想要的。如果我在运行时添加两个标记,那么它的集合中就有两个具有相应id的CategoryTag对象。问题是,在我调用SaveChanges时,相应的记录没有在我的多对多关系表(在本例中为ProposalCategoryTag)中创建。
知道我做错了什么吗?
更新:我没有在这上面找到任何东西,并且已经诉诸于像下面这样手动操作。我不喜欢这种方法,但它很有效。
<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
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