Asp.Net MVC 4 - 将对象模型添加到另一个对象模型中的ICollection

时间:2012-12-19 15:42:26

标签: asp.net-mvc model icollection

一些背景

我的Asp.Net MVC 4数据库第一个应用程序,提交和评论中有2个表。 (还有很多,但它们与这个问题无关)。任何给定的提交都可以包含任意数量的评论(一对多)。

我有一个提交详细信息页面,用户可以在其中打开一个jQuery对话框,其中包含部分视图,以便为提交添加注释。此部分视图绑定到为添加注释而创建的强类型视图模型。

表/模型

提交表

这是Submission表的类模型。 (为简单起见,我省略了一些属性)。

Partial Public Class Submission
    Public Property Submission_ID As Integer
    Public Property Submission_Hash As String
    Public Property Created As Nullable(Of Date)
    Public Property Modified As Date

    Public Overridable Property Comments As ICollection(Of Comment) = New HashSet(Of Comment)
End Class

评论表

这是Comment表的类模型。 (同样,为简单起见,我省略了一些属性)。

Partial Public Class Comment
    Public Property Comment_ID As Integer
    Public Property User_ID As Nullable(Of Integer)
    Public Property Comment_Type As Nullable(Of Integer)
    Public Property Comment1 As String
    Public Property Created As Nullable(Of Date)
    Public Property Modified As Date

    Public Overridable Property Comment_Type1 As Comment_Type
    Public Overridable Property User As User
    Public Overridable Property Submissions As ICollection(Of Submission) = New HashSet(Of Submission)
End Class

要求

我要做的是在给定提交的评论集合中添加新评论。

到目前为止......

到目前为止,我有一个添加注释对话框的视图模型,它在我的控制器中初始化,然后将填充的视图模型返回到控制器post方法。这是代码

视图模型

Public Class SubmissionAddCommentViewModel

    <Display(Name:="Submission")> _
    Public Property Submission_ID As Integer

    <Display(Name:="User")> _
    Public Property User_ID As Integer

    <Display(Name:="Comment type")> _
    Public Property Comment_Type As Integer

    <Required(ErrorMessage:="Please enter a comment.")> _
    <Display(Name:="Comment")> _
    Public Property Comment As String

End Class

ViewModel Builder

Public Class SubmissionAddCommentViewModel_Builder

    Implements IModelBuilder(Of SubmissionAddCommentViewModel, Comment)
    ReadOnly db As GeosightEntities
    ReadOnly submission As Submission

    Public Sub New(db As GeosightEntities, submission As Submission)
        Me.db = db
        Me.submission = submission
    End Sub

    Public Function CreateFrom(entity As Comment) As SubmissionAddCommentViewModel Implements IModelBuilder(Of SubmissionAddCommentViewModel, Comment).CreateFrom
        Dim model = New SubmissionAddCommentViewModel()

        model.Submission_ID = submission.Submission_ID
        model.User_ID = GetLoggedIn_ID()

        Return model
    End Function

    Public Function Rebuild(model As SubmissionAddCommentViewModel) As SubmissionAddCommentViewModel Implements IModelBuilder(Of SubmissionAddCommentViewModel, Comment).Rebuild
        Return model
    End Function

    Public Sub Add(model As SubmissionAddCommentViewModel)
        Dim comment As New Comment

        ' Map the ViewModel and Model fields
        comment.Comment_Type1 = If(IsNothing(model.Comment_Type), Nothing, db.Comment_Type.Find(model.Comment_Type))
        comment.User = db.Users.Find(model.User_ID)
        comment.Comment1 = model.Comment
        comment.Modified = Now

        ' Add the comment
        db.Submissions.Find(model.Submission_ID).Comments.Add(comment)
        db.SaveChanges()
    End Sub

End Class

控制器获取方法

Function AddComment(Optional ByVal id As Integer = Nothing) As ActionResult

    Dim commentAddView As New SubmissionAddCommentViewModel
    Dim submission As Submission = db.Submissions.Find(id)
    Dim comment As New Comment

    If IsNothing(submission) Then
        Return HttpNotFound()
    End If

    Me.builder_AddComment = New SubmissionAddCommentViewModel_Builder(db, submission)

    ' Create the instance of the submission add comment view model
    commentAddView = builder_AddComment.CreateFrom(comment)

    If Request.IsAjaxRequest Then
        Return PartialView("AddCommentPartial", commentAddView)
    End If

    Return View(commentAddView)
End Function

控制器发布方法

<HttpPost()> _
Function AddComment(ByVal commentAddView As SubmissionAddCommentViewModel) As ActionResult

    Dim comment As New Comment
    builder_AddComment = New SubmissionAddCommentViewModel_Builder(db, db.Submissions.Find(commentAddView.Submission_ID))

    ' Handle invalid comment models
    If Not ModelState.IsValid Then

        If Request.IsAjaxRequest Then
            Return PartialView("AddCommentPartial", commentAddView)
        End If

        Return View(commentAddView)
    End If

    ' Add the comment
    Me.builder_AddComment.Add(commentAddView)

    ' Display the successful message
    If Request.IsAjaxRequest Then
        Return PartialView("AddCommentSuccessPartial", commentAddView)
    End If

    Return RedirectToAction("Details", New With {.id = commentAddView.Submission_ID})

End Function

问题

在测试上述功能时,执行成功一直到ViewModel构建器中的db.SaveChanges(),但是一旦运行此行,执行就会停止。我不知道发生了什么,结果我完全陷入困境。

有谁知道 A)我是否会以正确的方式添加评论? B)为什么这一行在没有任何错误的情况下停止执行?


更新

感谢Peter Smith提出的关于在代码中加入Try Catch的建议,我不知道为什么我一开始没想到或者这样做。

我现在收到以下错误:

  

{MySql.Data.MySqlClient.MySqlException(0x80004005):您的SQL语法有错误;检查与MySQL服务器版本对应的手册,以便在'(SELECT“&amp; vbLf&amp;”Submission_CommentSubmission_ID,&amp; vbLf&amp;“{{1}附近使用正确的语法。在MySql.Data.MySqlClient.NativeDriver.GetResult(Int32&amp; affectedRow,Int64&amp; insertedId)的MySql.Data.MySqlClient.MySqlStream.ReadPacket()“&amp; vbCrLf&amp;”中的第1行“&amp; vbCrLf&amp;” )“&amp; vbCrLf&amp;”在MySql.Data.MySqlClient.Driver.GetResult(Int32 statementId,Int32&amp; affectedRows,Int64&amp; insertedId)“&amp; vbCrLf&amp;”at MySql.Data.MySqlClient.Driver.NextResult(Int32 statementId) ,布尔力)“&amp; vbCrLf&amp;”at MySql.Data.MySqlClient.MySqlDataReader.NextResult()“&amp; vbCrLf&amp;”at MySql.Data.MySqlClient.MySqlCommand.ExecuteReader(CommandBehavior behavior)“&amp; vbCrLf&amp; “at MySql.Data.MySqlClient.MySqlCommand.ExecuteReader()”&amp; vbCrLf&amp;“at MySql.Data.MySqlClient.MySqlCommand.ExecuteNonQuery()”&amp; vbCrLf&amp;“at MySql.Data.En tity.EFMySqlCommand.ExecuteNonQuery()“&amp; vbCrLf&amp; “在System.Data.Mapping.Update.Internal.DynamicUpdateCommand.Execute(UpdateTranslator translator,EntityConnection connection,Dictionary Submission_Comment 1 generatedValues)”&amp; vbCrLf&amp; “在System.Data.Mapping.Update.Internal.UpdateTranslator.Update(IEntityStateManager stateManager,IEntityAdapter adapter)}

1 个答案:

答案 0 :(得分:1)

我设法找到问题并实施解决方案。为了帮助那些可能遇到与我相同问题的人,这是我的解决方案。

在我的MySQL模式中,Submission和Comment表之间的中间表(Submission_Comment)有2列...... Submission_ID和Comment_ID。

当我设置表时,我将这些列设为外键但忘记将它们作为复合主键。 将2列作为复合主键修复了我的问题。