title: System.NullReferenceException Object reference not set to an instance of an object. on Model instantiation - SOMETIMES
body: <p>I'm getting System.NullReferenceException
  Object reference not set to an instance of an object on instantiation of a model but only sometimes. 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. </p>
  
  <p>Here is my error log from ELMAH:</p>
  
  <pre><code>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.&lt;BeginInvokeSynchronousActionMethod&gt;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.&lt;InvokeActionMethodFilterAsynchronouslyRecursive&gt;b__3d()
     at System.Web.Mvc.Async.AsyncControllerActionInvoker.AsyncInvocationWithFilters.&lt;&gt;c__DisplayClass46.&lt;InvokeActionMethodFilterAsynchronouslyRecursive&gt;b__3f()
     at System.Web.Mvc.Async.AsyncControllerActionInvoker.&lt;&gt;c__DisplayClass33.&lt;BeginInvokeActionMethodWithFilters&gt;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.&lt;&gt;c__DisplayClass21.&lt;&gt;c__DisplayClass2b.&lt;BeginInvokeAction&gt;b__1c()
     at System.Web.Mvc.Async.AsyncControllerActionInvoker.&lt;&gt;c__DisplayClass21.&lt;BeginInvokeAction&gt;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.&lt;BeginExecuteCore&gt;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.&lt;BeginExecute&gt;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.&lt;BeginProcessRequest&gt;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&amp; completedSynchronously)
  </code></pre>
  
  <p>Here is my code:</p>
  
  <pre><code>// Update Note
                  if (viewModel.ID != 0)
                  {
                      ReviewNote rn = _repository.Get&lt;ReviewNote&gt;(viewModel.ID);
                      MapViewModelToModel(rn, viewModel);
                      _repository.Update&lt;ReviewNote&gt;(rn);
                  }
                  // Create Note
                  else
                  {
                      ReviewAnswer ra = _repository.Get&lt;ReviewAnswer&gt;(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&lt;ReviewAnswer&gt;(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&lt;ReviewAnswer&gt;(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&lt;ReviewNote&gt;(rn);
                  }
  </code></pre>
  
  <p>The error is occuring at line 139 which is:</p>
  
  <pre><code>ReviewNote rn = new ReviewNote(); // 6th last line.
  </code></pre>
  
  <p>The ReviewNote Model code is:</p>
  
  <pre><code>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
      }
  }
  </code></pre>
  
  <p>Here is the BaseModel code:</p>
  
  <pre><code>public abstract class BaseModel
      {
          [NotMapped, JsonIgnore]
          public Alias Alias { get; set; }
  
          [NotMapped, JsonIgnore]
          public IDictionary&lt;string, object&gt; 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&lt;MenuItemClaim&gt; 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; }
      }
  </code></pre>
  
  <p>I can't see why there would be an NullReferenceException on the instantiation of ReviewNote at all.
  If anyone could offer a suggestion it would be most helpful because it's becoming more and more of an issue for my users.</p>
  
  <p>My project is ASP.NET MVC5 with Identity 2 and Entity Framework 6.2. I'm thinking the error only started after I upgraded Entity Framework 6.1 to 6.2, but it's just a guess.</p>
  
  <p>Thanks.</p>