【问题标题】:Adding Comment in SQL Server Error在 SQL Server 错误中添加注释
【发布时间】:2016-04-03 10:10:04
【问题描述】:

当我想向我的数据库添加评论时,我收到以下错误(顺序与数据库中的相同):

System.Data.SqlClient.SqlException was unhandled by user code
  Class=16
  ErrorCode=-2146232060
  HResult=-2146232060
  LineNumber=0
  Message=The parameterized query '(@UserId nvarchar(36),@TimeStamp datetime,@CategoryId int,@PostI' expects the parameter '@Comment', which was not supplied.
  Number=8178
  Procedure=""
  Server=MAXIM-HP\DATAMANAGEMENT
  Source=.Net SqlClient Data Provider
  State=1
  StackTrace:
       at System.Data.SqlClient.SqlConnection.OnError(SqlException exception, Boolean breakConnection, Action`1 wrapCloseInAction)
       at System.Data.SqlClient.SqlInternalConnection.OnError(SqlException exception, Boolean breakConnection, Action`1 wrapCloseInAction)
       at System.Data.SqlClient.TdsParser.ThrowExceptionAndWarning(TdsParserStateObject stateObj, Boolean callerHasConnectionLock, Boolean asyncClose)
       at System.Data.SqlClient.TdsParser.TryRun(RunBehavior runBehavior, SqlCommand cmdHandler, SqlDataReader dataStream, BulkCopySimpleResultSet bulkCopyHandler, TdsParserStateObject stateObj, Boolean& dataReady)
       at System.Data.SqlClient.SqlCommand.FinishExecuteReader(SqlDataReader ds, RunBehavior runBehavior, String resetOptionsString)
       at System.Data.SqlClient.SqlCommand.RunExecuteReaderTds(CommandBehavior cmdBehavior, RunBehavior runBehavior, Boolean returnStream, Boolean async, Int32 timeout, Task& task, Boolean asyncWrite, SqlDataReader ds, Boolean describeParameterEncryptionRequest)
       at System.Data.SqlClient.SqlCommand.RunExecuteReader(CommandBehavior cmdBehavior, RunBehavior runBehavior, Boolean returnStream, String method, TaskCompletionSource`1 completion, Int32 timeout, Task& task, Boolean asyncWrite)
       at System.Data.SqlClient.SqlCommand.InternalExecuteNonQuery(TaskCompletionSource`1 completion, String methodName, Boolean sendToPipe, Int32 timeout, Boolean asyncWrite)
       at System.Data.SqlClient.SqlCommand.ExecuteNonQuery()
       at BlogMaxim.Repositories.CommentRepository.Add(Comments comment) in C:\nmct\2e Jaar\1e sem\project\BlogMaxim\BlogMaxim\Repositories\CommentRepository.cs:line 98
       at BlogMaxim.Controllers.CommentController.AddComment(Comments comment) in C:\nmct\2e Jaar\1e sem\project\BlogMaxim\BlogMaxim\Controllers\CommentController.cs:line 43
       at lambda_method(Closure , ControllerBase , Object[] )
       at System.Web.Mvc.ActionMethodDispatcher.Execute(ControllerBase controller, Object[] parameters)
       at System.Web.Mvc.ReflectedActionDescriptor.Execute(ControllerContext controllerContext, IDictionary`2 parameters)
       at System.Web.Mvc.ControllerActionInvoker.InvokeActionMethod(ControllerContext controllerContext, ActionDescriptor actionDescriptor, IDictionary`2 parameters)
       at System.Web.Mvc.Async.AsyncControllerActionInvoker.<BeginInvokeSynchronousActionMethod>b__39(IAsyncResult asyncResult, ActionInvocation innerInvokeState)
       at System.Web.Mvc.Async.AsyncResultWrapper.WrappedAsyncResult`2.CallEndDelegate(IAsyncResult asyncResult)
       at System.Web.Mvc.Async.AsyncResultWrapper.WrappedAsyncResultBase`1.End()
       at System.Web.Mvc.Async.AsyncControllerActionInvoker.EndInvokeActionMethod(IAsyncResult asyncResult)
       at System.Web.Mvc.Async.AsyncControllerActionInvoker.AsyncInvocationWithFilters.<InvokeActionMethodFilterAsynchronouslyRecursive>b__3d()
       at System.Web.Mvc.Async.AsyncControllerActionInvoker.AsyncInvocationWithFilters.<>c__DisplayClass46.<InvokeActionMethodFilterAsynchronouslyRecursive>b__3f()
  InnerException: 

这是我将项目添加到数据库中的方法。

Add comments method

这是我创建的 Comments 对象:

namespace BlogMaxim.Models {
    public class Comments
    {
        public int Id { get; set; }
         public int CategoryId { get; set; }
         public int PostId { get; set; }
        public string Comment { get; set; }
         public string UserId { get; set; }
         public DateTime Timestamp { get; set; }
    } }

这是我的表格:

@model IEnumerable<BlogMaxim.Models.Comments>

@if (User.Identity.IsAuthenticated)
{
    <form method="post" action="/comment/addcomment">
        <label>Vul hier commentaar in: </label>
        <input type="hidden" width="150" name="PostId" value="@ViewBag.pId" />
        <input type="text" width="150" name="Comment" />
        <input type="submit" width="150" value="Toevoegen" />

    </form>

【问题讨论】:

  • 是comment.Comment 是否有空?
  • 请在您创建和初始化您传递给 Add() 方法的 Comments 对象的位置添加代码。
  • @AksheyBhat 已将其添加到帖子中。
  • 在您的表单中哪个文本框获取评论?
  • 请不要将代码发布为图片。这会阻止复制和粘贴现有代码以进行必要修改以提供答案的能力。

标签: sql-server asp.net-mvc sql-insert


【解决方案1】:

您在评论对象的 Comment 属性中获得了一个 NULL 值。

查看您的表单标记时,您的评论输入字段的名称(Description)似乎与您在视图模型中的名称不同。为了使 MVC 模型绑定正常工作,您的输入字段名称应与您的模型/视图模型属性名称匹配

将评论文本框的名称属性值更改为“Comment”,它应该可以工作。

<form method="post" action="/comment/addcomment">      
   <input type="text" name="Comment" />
   <input type="hidden" name="PostId" value="@ViewBag.pId" />
   <input type="submit" />
</form>

更进一步,每当您遇到此类错误时,您应该尝试输入breakpoints in your code 并尝试调试并查看您的变量的值。这将帮助您自己解决很多问题。

另外,我注意到的另一件事是,您使用的是comment.CategoryId,但在您的表单中,您没有任何输入字段来设置 CategoryId 的值。除非它是您数据库中的 NULLABLE 字段,否则您应该在保存评论之前将该值也从您的视图/设置该值传递给您的评论对象。

如果要设置查看

<form method="post" action="/comment/addcomment">      
   <input type="text" name="Comment" />
   <input type="hidden" name="PostId" value="@ViewBag.pId" />
   <input type="hidden" name="CategoryId" value="1" />
   <input type="hidden" value="@ViewBag.pId" />
   <input type="submit" />
</form>

我在表格中将 CategoryId 的值硬编码为 1。您可以从某处读取并设置它。

另外,您使用的是comment.UserId。因此,请确保在运行保存代码之前也设置了该值。

【讨论】:

  • 我已经这样做了,我已将我的表单添加到上面的帖子中。
  • 我更改了它,现在我得到一个类型为“System.NullReferenceException”的异常出现在 BlogMaxim.dll 中,但未在用户代码中处理附加信息:对象引用未设置为对象。
  • 您缺少其他属性值。请参阅我的更新答案。
  • 我评论中的 CategoryId 已被删除,因为我什至不知道为什么以及如何使用它(这毫无意义)。我不太明白您为评论“设置该值”是什么意思。UserId
  • 您的保存代码同时使用了 UserId 和 CategoryId。因此,您应该在执行保存代码之前设置评论对象的这些属性。我猜 UserId 将是当前登录用户的 ID。您应该知道要保存的 categoryId。如果您的 db 列允许 CategoryId 列的空值,您可以保持原样(NULL)。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2019-02-24
  • 1970-01-01
  • 2018-07-23
  • 1970-01-01
  • 1970-01-01
  • 2018-04-30
  • 1970-01-01
相关资源
最近更新 更多