title: LINQ to Entities returning "Object reference not set to an instance of an object."
body: <p>I have a piece of code that checks to see if a user is in our database using a view called <code>RESOURCE_V</code>. If not, the code uses Entity Framework to add the user to the database using the user's information from Active Directory. I would then like to re-query the <code>RESOURCE_V</code> view to get the submitted information. Upon doing so I am getting "Object reference not set to an instance of an object.". Here is the full code:</p>
  
  <pre><code>HALEntities context = new HALEntities();
              List&lt;RESOURCE_V&gt; userData = (from i in context.RESOURCE_V
                                           where i.NT_USER_N == Environment.UserName
                                           select i).ToList();
  
              // add user to RSRC table using Active Directory details
              if (userData.Count &gt; 0)
              {
                  PrincipalContext principleContext = new PrincipalContext(ContextType.Domain, HAL_Globals.domain);
                  UserPrincipal user = UserPrincipal.FindByIdentity(principleContext, IdentityType.SamAccountName, HAL_Globals.domain + "\\" + Environment.UserName);
                  RSRC rsrc = new RSRC();
  
                  rsrc.RSRC_I = context.RSRCs.Select(u =&gt; u.RSRC_I).Max() + 1;
                  rsrc.NT_USER_N = user.SamAccountName + "AAAA";
                  rsrc.FRST_N = user.GivenName;
                  rsrc.LAST_N = user.Surname;
                  rsrc.INIL_N = (user.MiddleName == null) ? "X" : user.MiddleName.Substring(0, 1);
                  rsrc.SHRT_N = user.GivenName.Substring(0, 1) + ((user.MiddleName == null) ? "X" : user.MiddleName.Substring(0, 1)) + user.Surname.Substring(0, 1);
                  rsrc.EMAIL_I = user.EmailAddress;
                  rsrc.TELE_I = user.VoiceTelephoneNumber.Replace("(", "").Replace(")", "").Replace("-", "");
                  rsrc.ACTV_F = true;
                  rsrc.CRTE_USER_I = Environment.UserName;
                  rsrc.CRTE_TS = DateTime.Now;
                  rsrc.UPDT_USER_I = Environment.UserName;
                  rsrc.UPDT_TS = DateTime.Now;
  
                  context.RSRCs.Add(rsrc);
                  context.SaveChanges();
                  userData = (from i in context.RESOURCE_V
                              where i.NT_USER_N == Environment.UserName + "AAAA"
                              select i).ToList();
              }
  </code></pre>
  
  <p>Notice the logic doesn't exactly match my description as I am using this code to test against my ID that already exists. The line that errors out is the very last statement in the <code>if</code> block:</p>
  
  <pre><code>userData = (from i in context.RESOURCE_V
                              where i.NT_USER_N == Environment.UserName + "AAAA"
                              select i).ToList();
  </code></pre>
  
  <p>I have tried recreating the Entity context, using different LINQ syntax, but have had no luck. Any help would be appreciated.</p>
  
  <p>Edit:</p>
  
  <p>As requested, here is the stack trace:</p>
  
  <pre><code>   at System.RuntimeTypeHandle.CreateInstance(RuntimeType type, Boolean publicOnly, Boolean noCheck, Boolean&amp; canBeCached, RuntimeMethodHandleInternal&amp; ctor, Boolean&amp; bNeedSecurityCheck)
     at System.RuntimeType.CreateInstanceSlow(Boolean publicOnly, Boolean skipCheckThis, Boolean fillCache, StackCrawlMark&amp; stackMark)
     at System.RuntimeType.CreateInstanceDefaultCtor(Boolean publicOnly, Boolean skipCheckThis, Boolean fillCache, StackCrawlMark&amp; stackMark)
     at System.Activator.CreateInstance(Type type, Boolean nonPublic)
     at System.RuntimeType.CreateInstanceImpl(BindingFlags bindingAttr, Binder binder, Object[] args, CultureInfo culture, Object[] activationAttributes, StackCrawlMark&amp; stackMark)
     at System.Activator.CreateInstance(Type type, BindingFlags bindingAttr, Binder binder, Object[] args, CultureInfo culture, Object[] activationAttributes)
     at System.Activator.CreateInstance(Type type, Object[] args)
     at System.Xaml.Schema.SafeReflectionInvoker.CreateInstanceCritical(Type type, Object[] arguments)
     at System.Xaml.Schema.SafeReflectionInvoker.CreateInstance(Type type, Object[] arguments)
     at System.Xaml.Schema.XamlTypeInvoker.CreateInstance(Object[] arguments)
     at MS.Internal.Xaml.Runtime.ClrObjectRuntime.CreateInstanceWithCtor(XamlType xamlType, Object[] args)
     at MS.Internal.Xaml.Runtime.ClrObjectRuntime.CreateInstance(XamlType xamlType, Object[] args)
     at MS.Internal.Xaml.Runtime.PartialTrustTolerantRuntime.CreateInstance(XamlType xamlType, Object[] args)
     at System.Xaml.XamlObjectWriter.Logic_CreateAndAssignToParentStart(ObjectWriterContext ctx)
     at System.Xaml.XamlObjectWriter.WriteStartMember(XamlMember property)
     at System.Xaml.XamlWriter.WriteNode(XamlReader reader)
     at System.Windows.Markup.WpfXamlLoader.TransformNodes(XamlReader xamlReader, XamlObjectWriter xamlWriter, Boolean onlyLoadOneNode, Boolean skipJournaledProperties, Boolean shouldPassLineNumberInfo, IXamlLineInfo xamlLineInfo, IXamlLineInfoConsumer xamlLineInfoConsumer, XamlContextStack`1 stack, IStyleConnector styleConnector)
     at System.Windows.Markup.WpfXamlLoader.Load(XamlReader xamlReader, IXamlObjectWriterFactory writerFactory, Boolean skipJournaledProperties, Object rootObject, XamlObjectWriterSettings settings, Uri baseUri)
     at System.Windows.Markup.WpfXamlLoader.LoadBaml(XamlReader xamlReader, Boolean skipJournaledProperties, Object rootObject, XamlAccessLevel accessLevel, Uri baseUri)
     at System.Windows.Markup.XamlReader.LoadBaml(Stream stream, ParserContext parserContext, Object parent, Boolean closeStream)
     at System.Windows.Application.LoadBamlStreamWithSyncInfo(Stream stream, ParserContext pc)
     at System.Windows.Application.LoadComponent(Uri resourceLocator, Boolean bSkipJournaledProperties)
     at System.Windows.Application.DoStartup()
     at System.Windows.Application.&lt;.ctor&gt;b__1(Object unused)
     at System.Windows.Threading.ExceptionWrapper.InternalRealCall(Delegate callback, Object args, Int32 numArgs)
     at MS.Internal.Threading.ExceptionFilterHelper.TryCatchWhen(Object source, Delegate method, Object args, Int32 numArgs, Delegate catchHandler)
     at System.Windows.Threading.DispatcherOperation.InvokeImpl()
     at System.Windows.Threading.DispatcherOperation.InvokeInSecurityContext(Object state)
     at System.Threading.ExecutionContext.RunInternal(ExecutionContext executionContext, ContextCallback callback, Object state, Boolean preserveSyncCtx)
     at System.Threading.ExecutionContext.Run(ExecutionContext executionContext, ContextCallback callback, Object state, Boolean preserveSyncCtx)
     at System.Threading.ExecutionContext.Run(ExecutionContext executionContext, ContextCallback callback, Object state)
     at System.Windows.Threading.DispatcherOperation.Invoke()
     at System.Windows.Threading.Dispatcher.ProcessQueue()
     at System.Windows.Threading.Dispatcher.WndProcHook(IntPtr hwnd, Int32 msg, IntPtr wParam, IntPtr lParam, Boolean&amp; handled)
     at MS.Win32.HwndWrapper.WndProc(IntPtr hwnd, Int32 msg, IntPtr wParam, IntPtr lParam, Boolean&amp; handled)
     at MS.Win32.HwndSubclass.DispatcherCallbackOperation(Object o)
     at System.Windows.Threading.ExceptionWrapper.InternalRealCall(Delegate callback, Object args, Int32 numArgs)
     at MS.Internal.Threading.ExceptionFilterHelper.TryCatchWhen(Object source, Delegate method, Object args, Int32 numArgs, Delegate catchHandler)
     at System.Windows.Threading.Dispatcher.LegacyInvokeImpl(DispatcherPriority priority, TimeSpan timeout, Delegate method, Object args, Int32 numArgs)
     at MS.Win32.HwndSubclass.SubclassWndProc(IntPtr hwnd, Int32 msg, IntPtr wParam, IntPtr lParam)
     at MS.Win32.UnsafeNativeMethods.DispatchMessage(MSG&amp; msg)
     at System.Windows.Threading.Dispatcher.PushFrameImpl(DispatcherFrame frame)
     at System.Windows.Threading.Dispatcher.PushFrame(DispatcherFrame frame)
     at System.Windows.Threading.Dispatcher.Run()
     at System.Windows.Application.RunDispatcher(Object ignore)
     at System.Windows.Application.RunInternal(Window window)
     at System.Windows.Application.Run(Window window)
     at System.Windows.Application.Run()
     at HAL.App.Main() in c:\HAL\HAL_PROD\HAL\obj\Debug\App.g.cs:line 0
     at System.AppDomain._nExecuteAssembly(RuntimeAssembly assembly, String[] args)
     at System.AppDomain.nExecuteAssembly(RuntimeAssembly assembly, String[] args)
     at System.Runtime.Hosting.ManifestRunner.Run(Boolean checkAptModel)
     at System.Runtime.Hosting.ManifestRunner.ExecuteAsAssembly()
     at System.Runtime.Hosting.ApplicationActivator.CreateInstance(ActivationContext activationContext, String[] activationCustomData)
     at System.Runtime.Hosting.ApplicationActivator.CreateInstance(ActivationContext activationContext)
     at System.Activator.CreateInstance(ActivationContext activationContext)
     at Microsoft.VisualStudio.HostingProcess.HostProc.RunUsersAssemblyDebugInZone()
     at System.Threading.ThreadHelper.ThreadStart_Context(Object state)
     at System.Threading.ExecutionContext.RunInternal(ExecutionContext executionContext, ContextCallback callback, Object state, Boolean preserveSyncCtx)
     at System.Threading.ExecutionContext.Run(ExecutionContext executionContext, ContextCallback callback, Object state, Boolean preserveSyncCtx)
     at System.Threading.ExecutionContext.Run(ExecutionContext executionContext, ContextCallback callback, Object state)
     at System.Threading.ThreadHelper.ThreadStart()
  </code></pre>
  
  <p>Edit 2: The Inner Exception Stack Trace:</p>
  
  <pre><code>at System.Data.EntityKey.AddHashValue(Int32 hashCode, Object keyValue)
     at System.Data.EntityKey.GetHashCode()
     at System.Collections.Generic.GenericEqualityComparer`1.GetHashCode(T obj)
     at System.Collections.Generic.Dictionary`2.FindEntry(TKey key)
     at System.Collections.Generic.Dictionary`2.TryGetValue(TKey key, TValue&amp; value)
     at System.Data.Objects.ObjectStateManager.TryGetEntityEntry(EntityKey key, EntityEntry&amp; entry)
     at System.Data.Common.Internal.Materialization.Shaper.HandleEntityAppendOnly[TEntity](Func`2 constructEntityDelegate, EntityKey entityKey, EntitySet entitySet)
     at lambda_method(Closure , Shaper )
     at System.Data.Common.Internal.Materialization.Coordinator`1.ReadNextElement(Shaper shaper)
     at System.Data.Common.Internal.Materialization.Shaper`1.SimpleEnumerator.MoveNext()
     at System.Collections.Generic.List`1..ctor(IEnumerable`1 collection)
     at System.Linq.Enumerable.ToList[TSource](IEnumerable`1 source)
     at HAL.HAL_CurrentUser..ctor(SqlConnection currentServerConnection) in c:\HAL\HAL_PROD\HAL\Global Classes\HAL_CurrentUser.cs:line 86
     at HAL.HAL_CurrentUser.get_Instance() in c:\HAL\HAL_PROD\HAL\Global Classes\HAL_CurrentUser.cs:line 46
     at HAL.WelcomeViewModel..ctor() in c:\HAL\HAL_PROD\HAL\HAL Classes\Welcome\WelcomeViewModel.cs:line 21
     at HAL.Welcome..ctor() in c:\HAL\HAL_PROD\HAL\HAL Classes\Welcome\Welcome.xaml.cs:line 26
     at HAL.Navigation..ctor() in c:\HAL\HAL_PROD\HAL\Navigation.xaml.cs:line 17
  </code></pre>
  
  <p>Edit 3:</p>
  
  <p>After playing around with the values being queried in the second LINQ query I have determined the issue is being caused by the fact that I am filtering on the new ID in the where clause of the LINQ query. If I hard-code another ID in the query it works and the error is not thrown. I have determined the new ID is in fact being added to the database.</p>