LINQ to Entities返回"对象引用未设置为对象的实例。"

时间:2014-04-17 15:02:08

标签: c# linq entity-framework linq-to-entities

我有一段代码使用名为RESOURCE_V的视图检查用户是否在我们的数据库中。如果没有,代码使用Entity Framework使用来自Active Directory的用户信息将用户添加到数据库。然后,我想重新查询RESOURCE_V视图以获取提交的信息。这样做后,我得到的对象引用未设置为对象的实例。"。这是完整的代码:

HALEntities context = new HALEntities();
            List<RESOURCE_V> 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 > 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 => 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();
            }

请注意,逻辑与我的描述完全匹配,因为我使用此代码来测试已存在的ID。错误输出的行是if块中的最后一个语句:

userData = (from i in context.RESOURCE_V
                            where i.NT_USER_N == Environment.UserName + "AAAA"
                            select i).ToList();

我尝试使用不同的LINQ语法重新创建实体上下文,但没有运气。任何帮助将不胜感激。

编辑:

根据要求,这是堆栈跟踪:

   at System.RuntimeTypeHandle.CreateInstance(RuntimeType type, Boolean publicOnly, Boolean noCheck, Boolean& canBeCached, RuntimeMethodHandleInternal& ctor, Boolean& bNeedSecurityCheck)
   at System.RuntimeType.CreateInstanceSlow(Boolean publicOnly, Boolean skipCheckThis, Boolean fillCache, StackCrawlMark& stackMark)
   at System.RuntimeType.CreateInstanceDefaultCtor(Boolean publicOnly, Boolean skipCheckThis, Boolean fillCache, StackCrawlMark& stackMark)
   at System.Activator.CreateInstance(Type type, Boolean nonPublic)
   at System.RuntimeType.CreateInstanceImpl(BindingFlags bindingAttr, Binder binder, Object[] args, CultureInfo culture, Object[] activationAttributes, StackCrawlMark& 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.<.ctor>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& handled)
   at MS.Win32.HwndWrapper.WndProc(IntPtr hwnd, Int32 msg, IntPtr wParam, IntPtr lParam, Boolean& 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& 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()

编辑2:内部异常堆栈跟踪:

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& value)
   at System.Data.Objects.ObjectStateManager.TryGetEntityEntry(EntityKey key, EntityEntry& 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

编辑3:

在使用第二个LINQ查询中查询的值之后,我确定问题是由于我在LINQ查询的where子句中过滤新ID这一事实引起的。如果我在查询中硬编码另一个ID它可以工作,并且不会抛出错误。我已确定新ID实际上已添加到数据库中。

2 个答案:

答案 0 :(得分:6)

实体具有复合键,当您保存新实体时,其中一个键列为null。 EF不支持可空键(它会抛出),但显然EF中存在一个错误,在这种情况下不会检查此条件,因此也不会检查NRE。您需要确保不在主键列中返回空值。

答案 1 :(得分:0)

我遇到了同样的问题。我的收集类型的类字段是空的。我努力解决这个问题。 最后错误是拼写错误 - 我正在使用new创建对象,同时为类字段名称进行本地声明,然后它超出了本地范围。 我知道它没有回答这个主题,而是重新检查代码是否存在此类错误。 对不起,我真的很想帮助像我一样有类似问题的其他人。