LINQ to Entitys return“;对象引用未设置为对象的实例&”;

本文关键字:对象 实例 设置 Entitys to return 对象引用 LINQ | 更新日期: 2023-09-27 17:58:52

我有一段代码,它使用一个名为RESOURCE_V的视图来检查用户是否在我们的数据库中。如果没有,代码将使用实体框架使用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实际上正在添加到数据库中。

LINQ to Entitys return“;对象引用未设置为对象的实例&”;

实体有一个复合键,保存新实体时,其中一个键列为null。EF不支持可为null的密钥(它抛出),但显然EF中有一个错误,在这个特定的场景中没有检查这个条件,因此也没有检查NRE。您需要确保主键列中没有返回null值。

我也遇到了同样的问题。集合类型的类字段为空。我费了很大劲才解决这个问题。最后,错误是打字错误——我用new创建对象,同时为类字段名进行本地声明,然后它超出了本地范围。我知道它不能回答这个主题,但作为一个要点,重新检查代码中是否存在此类错误。对不起,我真的很想帮助其他像我一样的人解决类似的问题。