[英]System.NullReferenceException Object reference not set to an instance of an object. on Model instantiation - SOMETIMES
I'm getting System.NullReferenceException Object reference not set to an instance of an object on instantiation of a model but only sometimes. 我收到System.NullReferenceException对象引用未设置为模型实例化时的对象实例,但有时只是。 My users are experiencing the error sometimes, but once they resubmit the exception does not occur.
我的用户有时会遇到错误,但一旦他们重新提交,则不会发生异常。 I can't figure out why the error is happening.
我无法弄清楚错误发生的原因。
Here is my error log from ELMAH: 这是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)
Here is my code: 这是我的代码:
// 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);
}
The error is occuring at line 139 which is: 错误发生在第139行,即:
ReviewNote rn = new ReviewNote(); // 6th last line.
The ReviewNote Model code is: ReviewNote模型代码是:
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
}
}
Here is the BaseModel code: 这是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; }
}
I can't see why there would be an NullReferenceException on the instantiation of ReviewNote at all. 我无法理解为什么在ReviewNote的实例化中会出现NullReferenceException。 If anyone could offer a suggestion it would be most helpful because it's becoming more and more of an issue for my users.
如果有人能提出建议,那将是最有帮助的,因为它对我的用户来说越来越成为一个问题。
My project is ASP.NET MVC5 with Identity 2 and Entity Framework 6.2. 我的项目是带有Identity 2和Entity Framework 6.2的ASP.NET MVC5。 I'm thinking the error only started after I upgraded Entity Framework 6.1 to 6.2, but it's just a guess.
我认为错误只是在我将Entity Framework 6.1升级到6.2之后才开始,但这只是猜测。
Thanks. 谢谢。
As commenters have noted, there doesn't seem to be anything in the construction of ReviewNote
that should generate a NullReferenceException
, and no code outside your own is showing up in the stacktrace. 正如评论者所指出的那样,在构造
ReviewNote
似乎没有任何东西可以产生NullReferenceException
,并且在你自己的代码中没有任何代码出现在stacktrace中。
I have had issues in the past where the line number given in a stacktrace was a few lines off from where the actual error occurred. 过去我遇到过一些问题,堆栈跟踪中给出的行号与发生实际错误的位置相距几行。 If you can't catch it with a debugger attached, all I can suggest is that you add some kind of information to supplement the line number.
如果您无法使用附加的调试器来捕获它,我可以建议您添加某种信息来补充行号。 An easy way to do this is an incrementing integer:
一个简单的方法是递增整数:
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);
}
The value of debugId
will tell you which line the failure occurred on debugId
的值将告诉您发生故障的行
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.