我收到System.NullReferenceException 对象引用未设置为模型实例化时的对象实例,但有时仅设置为对象实例。我的用户有时会遇到错误,但一旦他们重新提交,则不会发生异常。我无法弄清楚错误发生的原因。
以下是ELMAH的错误日志:
System.NullReferenceException: Object reference not set to an instance of an object.
at Plus.Controllers.Review.ReviewNoteController.Save(ReviewNoteViewModel viewModel) in C:\Users\Rhys\Documents\Development\witplus-master\Plus\Controllers\Review\ReviewNoteController.cs:line 139
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()
at System.Web.Mvc.Async.AsyncControllerActionInvoker.<>c__DisplayClass33.<BeginInvokeActionMethodWithFilters>b__32(IAsyncResult asyncResult)
at System.Web.Mvc.Async.AsyncResultWrapper.WrappedAsyncResult`1.CallEndDelegate(IAsyncResult asyncResult)
at System.Web.Mvc.Async.AsyncResultWrapper.WrappedAsyncResultBase`1.End()
at System.Web.Mvc.Async.AsyncControllerActionInvoker.EndInvokeActionMethodWithFilters(IAsyncResult asyncResult)
at System.Web.Mvc.Async.AsyncControllerActionInvoker.<>c__DisplayClass21.<>c__DisplayClass2b.<BeginInvokeAction>b__1c()
at System.Web.Mvc.Async.AsyncControllerActionInvoker.<>c__DisplayClass21.<BeginInvokeAction>b__1e(IAsyncResult asyncResult)
at System.Web.Mvc.Async.AsyncResultWrapper.WrappedAsyncResult`1.CallEndDelegate(IAsyncResult asyncResult)
at System.Web.Mvc.Async.AsyncResultWrapper.WrappedAsyncResultBase`1.End()
at System.Web.Mvc.Async.AsyncControllerActionInvoker.EndInvokeAction(IAsyncResult asyncResult)
at System.Web.Mvc.Controller.<BeginExecuteCore>b__1d(IAsyncResult asyncResult, ExecuteCoreState innerState)
at System.Web.Mvc.Async.AsyncResultWrapper.WrappedAsyncVoid`1.CallEndDelegate(IAsyncResult asyncResult)
at System.Web.Mvc.Async.AsyncResultWrapper.WrappedAsyncResultBase`1.End()
at System.Web.Mvc.Controller.EndExecuteCore(IAsyncResult asyncResult)
at System.Web.Mvc.Controller.<BeginExecute>b__15(IAsyncResult asyncResult, Controller controller)
at System.Web.Mvc.Async.AsyncResultWrapper.WrappedAsyncVoid`1.CallEndDelegate(IAsyncResult asyncResult)
at System.Web.Mvc.Async.AsyncResultWrapper.WrappedAsyncResultBase`1.End()
at System.Web.Mvc.Controller.EndExecute(IAsyncResult asyncResult)
at System.Web.Mvc.Controller.System.Web.Mvc.Async.IAsyncController.EndExecute(IAsyncResult asyncResult)
at System.Web.Mvc.MvcHandler.<BeginProcessRequest>b__5(IAsyncResult asyncResult, ProcessRequestState innerState)
at System.Web.Mvc.Async.AsyncResultWrapper.WrappedAsyncVoid`1.CallEndDelegate(IAsyncResult asyncResult)
at System.Web.Mvc.Async.AsyncResultWrapper.WrappedAsyncResultBase`1.End()
at System.Web.Mvc.MvcHandler.EndProcessRequest(IAsyncResult asyncResult)
at System.Web.Mvc.MvcHandler.System.Web.IHttpAsyncHandler.EndProcessRequest(IAsyncResult result)
at System.Web.HttpApplication.CallHandlerExecutionStep.System.Web.HttpApplication.IExecutionStep.Execute()
at System.Web.HttpApplication.ExecuteStep(IExecutionStep step, Boolean& completedSynchronously)
这是我的代码:
// Update Note
if (viewModel.ID != 0)
{
ReviewNote rn = _repository.Get<ReviewNote>(viewModel.ID);
MapViewModelToModel(rn, viewModel);
_repository.Update<ReviewNote>(rn);
}
// Create Note
else
{
ReviewAnswer ra = _repository.Get<ReviewAnswer>(viewModel.AnswerId);
bool newAnswer = false;
// Check if practice or checklists
if (viewModel.Referrer == Referrer.ReviewPractice)
{
// Create a new answer if it hasn't been answered yet. Could have made a bool in the GET method, but it's best to recheck to make sure no-one has answered in the mean time.
if (hasNoAnswer_PracticeLevel(viewModel.QuestionId))
{
ra = new ReviewAnswer();
ra.entityLevelAudit = true;
ra.entityId = this.LoggedInEntity.EntityId;
ra.questionId = viewModel.QuestionId;
ra.lastUpdateDate = DateTime.Now;
_repository.Save<ReviewAnswer>(ra);
newAnswer = true;
viewModel.AnswerId = ra.Id;
}
}
else
{
// Create a new answer if it hasn't been answered yet.
if (hasNoAnswer_Checklist(viewModel.QuestionId))
{
ra = new ReviewAnswer();
ra.entityLevelAudit = false;
ra.entityId = this.LoggedInEntity.EntityId;
ra.questionId = viewModel.QuestionId;
ra.userId = this.SelectedUser.UserId;
ra.lastUpdateDate = DateTime.Now;
_repository.Save<ReviewAnswer>(ra);
newAnswer = true;
viewModel.AnswerId = ra.Id;
}
}
ReviewNote rn = new ReviewNote();
rn.auditID = ra.Id;
rn.Type = (int)this.LoggedInUser.ReviewTypeId; //Audit Note type is the user audit type
MapViewModelToModel(rn, viewModel);
_repository.Save<ReviewNote>(rn);
}
第139行出现错误:
ReviewNote rn = new ReviewNote(); // 6th last line.
ReviewNote Model代码是:
using Plus.Models.UserModel;
using System;
using System.ComponentModel;
using System.ComponentModel.DataAnnotations;
using System.ComponentModel.DataAnnotations.Schema;
using System.Data.Entity;
using System.Web;
using System.Web.Mvc;
namespace Plus.Models.Review
{
public class ReviewNote : BaseModel
{
[Key, DatabaseGenerated(DatabaseGeneratedOption.Identity), Column("AuditNoteId")]
public int ID { get; set; } // AuditNoteId
public int auditID { get; set; }
[ForeignKey("auditID")]
public virtual ReviewAnswer Answer { get; set; }
[StringLength(10000), AllowHtml, Column("noteText")]
public string Text { get; set; } //noteText
[StringLength(200), Column("noteFile")]
public string URL { get; set; } //noteFile
[DataType(DataType.DateTime), Column("lastUpdateDate")]
public DateTime LastUpdated { get; set; }//lastUpdateDate
[Column("showNoteToAll")]
public bool VisibleToAll { get; set; } //ShowNoteToAll
[Required]
public int NoteBy { get; set; } //NoteBy
[ForeignKey("NoteBy")]
public virtual User By { get; set; }
[Column("noteType")]
public int Type { get; set; } //NoteType
}
}
这是BaseModel代码:
public abstract class BaseModel
{
[NotMapped, JsonIgnore]
public Alias Alias { get; set; }
[NotMapped, JsonIgnore]
public IDictionary<string, object> AliasDictionary { get; set; }
[NotMapped, JsonIgnore]
public AppUserDTO LoggedInAppUser { get; set; }
[NotMapped, JsonIgnore]
public UserDTO LoggedInUser { get; set; }
[NotMapped, JsonIgnore]
public EntityDTO LoggedInEntity { get; set; }
[NotMapped, JsonIgnore]
public ResourceDTO LoggedInUsersResource { get; set; }
[NotMapped, JsonIgnore]
public virtual ICollection<MenuItemClaim> MenuSystemTreeClaims { get; set; }
[NotMapped, JsonIgnore]
public IStateProvider UserSession { get; set; }
[NotMapped, JsonIgnore]
public UserDTO SelectedUser { get; set; }
[NotMapped, JsonIgnore]
public TermsAndConditions TAC { get; set; }
[NotMapped, JsonIgnore]
public string PageClaimValue { get; set; }
}
我无法理解为什么在ReviewNote的实例化中会出现NullReferenceException。 如果有人可以提供建议,那么这将是最有帮助的,因为它对我的用户来说越来越成为一个问题。
我的项目是带有Identity 2和Entity Framework 6.2的ASP.NET MVC5。我认为错误只是在我将Entity Framework 6.1升级到6.2之后才开始,但这只是猜测。
感谢。
答案 0 :(得分:2)
正如评论者所指出的那样,ReviewNote
的构造中似乎没有任何内容可以生成NullReferenceException
,并且您自己的代码不会出现在堆栈跟踪中。
过去我遇到过一些问题,堆栈跟踪中的行号与发生实际错误的位置相距几行。如果您无法使用附加的调试器来捕获它,我可以建议您添加某种信息来补充行号。一个简单的方法是递增整数:
int debugId = 0;
try
{
ReviewNote rn = new ReviewNote(); // debugId == 0
++debugId;
rn.auditID = ra.Id; // debugId == 1
++debugId;
rn.Type = (int)this.LoggedInUser.ReviewTypeId; // debugId == 2
++debugId;
MapViewModelToModel(rn, viewModel); // debugId == 3
++debugId;
_repository.Save<ReviewNote>(rn); // debugId == 4
}
catch (NullReferenceException nre)
{
throw new Exception("debugId:" + debugId, nre);
}
debugId
的值将告诉您