简体   繁体   English

从EF4升级后,在EF6中查询数据的空引用异常

[英]Null Reference Exception querying data in EF6 after upgrading from EF4

I'm having some trouble getting data out of my entity framework context. 我在从实体框架上下文中获取数据时遇到了一些麻烦。 I'm upgrading my application from entity framework 4 to 6 and it has not been a party. 我正在将我的应用程序从实体框架4升级到6并且它还没有成为派对。

Right now, if I try to query any records from my database I get a null reference exception. 现在,如果我尝试查询数据库中的任何记录,我会得到一个空引用异常。

DBSet<EntityObject> test1 = context.EntityObjects;
List<EntityObject> test2 = test1.ToList();

The first line runs without error. 第一行运行没有错误。 The second line throws a System.NullReferenceException with the following stack trace: 第二行抛出System.NullReferenceException,其中包含以下堆栈跟踪:

at System.Data.Entity.Core.Metadata.Edm.OSpaceTypeFactory.TypesMatchByConvention(Type type, EdmType cspaceType)
at System.Data.Entity.Core.Metadata.Edm.OSpaceTypeFactory.TryCreateStructuralType(Type type, StructuralType cspaceType, EdmType& newOSpaceType)
at System.Data.Entity.Core.Metadata.Edm.OSpaceTypeFactory.TryCreateType(Type type, EdmType cspaceType)
at System.Data.Entity.Core.Metadata.Edm.ObjectItemConventionAssemblyLoader.LoadTypesFromAssembly()
at System.Data.Entity.Core.Metadata.Edm.ObjectItemAssemblyLoader.Load()
at System.Data.Entity.Core.Metadata.Edm.AssemblyCache.LoadAssembly(Assembly assembly, Boolean loadReferencedAssemblies, ObjectItemLoadingSessionData loadingData)
at System.Data.Entity.Core.Metadata.Edm.AssemblyCache.LoadAssembly(Assembly assembly, Boolean loadReferencedAssemblies, KnownAssembliesSet knownAssemblies, EdmItemCollection edmItemCollection, Action`1 logLoadMessage, Object& loaderCookie, Dictionary`2& typesInLoading, List`1& errors)
at System.Data.Entity.Core.Metadata.Edm.ObjectItemCollection.LoadAssemblyFromCache(Assembly assembly, Boolean loadReferencedAssemblies, EdmItemCollection edmItemCollection, Action`1 logLoadMessage)
at System.Data.Entity.Core.Metadata.Edm.ObjectItemCollection.ExplicitLoadFromAssembly(Assembly assembly, EdmItemCollection edmItemCollection, Action`1 logLoadMessage)
at System.Data.Entity.Core.Metadata.Edm.MetadataWorkspace.ExplicitLoadFromAssembly(Assembly assembly, ObjectItemCollection collection, Action`1 logLoadMessage)
at System.Data.Entity.Core.Metadata.Edm.MetadataWorkspace.LoadFromAssembly(Assembly assembly, Action`1 logLoadMessage)
at System.Data.Entity.Core.Metadata.Edm.MetadataWorkspace.LoadFromAssembly(Assembly assembly)
at System.Data.Entity.Internal.InternalContext.TryUpdateEntitySetMappingsForType(Type entityType)
at System.Data.Entity.Internal.InternalContext.UpdateEntitySetMappingsForType(Type entityType)
at System.Data.Entity.Internal.InternalContext.GetEntitySetAndBaseTypeForType(Type entityType)
at System.Data.Entity.Internal.Linq.InternalSet`1.Initialize()
at System.Data.Entity.Internal.Linq.InternalSet`1.GetEnumerator()
at System.Data.Entity.Infrastructure.DbQuery`1.System.Collections.Generic.IEnumerable<TResult>.GetEnumerator()
at System.Collections.Generic.List`1..ctor(IEnumerable`1 collection)
at System.Linq.Enumerable.ToList[TSource](IEnumerable`1 source)
at ConnectServer.ConnectModule.handleReceive(Message message, ClientConnection client) in c:\Users\Eric Bowman\Documents\Visual Studio 2012\Projects\NXConnect_ME578_Interoperability\CADInteroperabilityCATIA\ConnectServer\ConnectModule.cs:line 137

My closes guess right now is that there's a problem with my connection string which is preventing the context from connecting with the database, so here is my config file: 我现在关闭的猜测是我的连接字符串存在问题,这阻止了上下文与数据库的连接,所以这是我的配置文件:

<?xml version="1.0" encoding="utf-8"?>
   <configuration>
      <configSections>
         <section name="entityFramework" type="System.Data.Entity.Internal.ConfigFile.EntityFrameworkSection, EntityFramework, Version=6.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" requirePermission="false" />
         <!-- For more information on Entity Framework configuration, visit http://go.microsoft.com/fwlink/?LinkID=237468 -->
      </configSections>
      <connectionStrings>
         <add name="FancyEntities" connectionString="metadata=res://*/ConnectData.csdl|res://*/ConnectData.ssdl|res://*/ConnectData.msl;provider=System.Data.SqlClient;provider connection string=&quot;data source=localhost,1433;initial catalog=Fancy_Dev;Persist Security Info=True;User ID=******;Password=************;MultipleActiveResultSets=True&quot;"
  providerName="System.Data.EntityClient"/>
      </connectionStrings>
      <entityFramework>
         <defaultConnectionFactory type="System.Data.Entity.Infrastructure.SqlConnectionFactory, EntityFramework" />
         <providers>
            <provider invariantName="System.Data.SqlClient" type="System.Data.Entity.SqlServer.SqlProviderServices, EntityFramework.SqlServer" />
         </providers>
      </entityFramework>
      <startup>
         <supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.5" />
      </startup>

Am I missing something in there? 我错过了那里的东西吗? Could it be something else? 它可能是别的吗?

UPDATE UPDATE

The connection string was bad, but even after fixing it I get exactly the same error. 连接字符串很糟糕,但即使在修复它之后我也会得到完全相同的错误。 I can open a connection to the database, but when I try to look at any of the collections in the context, it throws a null reference exception. 我可以打开与数据库的连接,但是当我尝试查看上下文中的任何集合时,它会抛出一个空引用异常。

This is very frustrating 这非常令人沮丧

Another Update 另一个更新

I haven't seen much help so I'm posting some of the information I've found. 我没有看到太多的帮助,所以我发布了一些我发现的信息。

I found the Entity Framework Source and this is the method that crashes: 我找到了Entity Framework Source,这是崩溃的方法:

    internal static bool TypesMatchByConvention(Type type, EdmType cspaceType)
    {
        return type.Name == cspaceType.Name;
    }

And here is the previous code block that calls the method: 以下是调用该方法的前一个代码块:

        if (cspaceType.BaseType != null)
        {
            if (TypesMatchByConvention(type.BaseType, cspaceType.BaseType))
            {
                TrackClosure(type.BaseType);
                referenceResolutionListForCurrentType.Add(
                    () => ospaceType.BaseType = ResolveBaseType((StructuralType)cspaceType.BaseType, type));
            }
            else
            {
                var message = Strings.Validator_OSpace_Convention_BaseTypeIncompatible(
                    type.BaseType.FullName, type.FullName, cspaceType.BaseType.FullName);
                LogLoadMessage(message, cspaceType);
                return false;
            }
        }

Note that it checks cspaceType.BaseType for null but not type.BaseType. 请注意,它检查cspaceType.BaseType是否为null但不是type.BaseType。

I created a fresh project with the same entity model and it works fine, so it's something to do with my specific settings or project or something. 我使用相同的实体模型创建了一个新项目,它工作正常,因此它与我的特定设置或项目或其他东西有关。

I had a bad connections string when I posted this, so watch out for that but it wasn't actually the problem 当我发布这个时,我的连接字符串很糟糕,所以请注意,但实际上并不是问题所在

the problem was a name conflict. 问题是名称冲突。 One of my classes in Entity Framework had the same name as a class in one of my other references. 我在Entity Framework中的一个类与我的其他一个引用中的类具有相同的名称。

So, as a general practice I recommend giving each of your Entity Framework classes a prefix to make absolutely sure it's never the same as any class you might use in any library ever. 因此,作为一般惯例,我建议为每个Entity Framework类提供一个前缀,以确保它永远不会与您在任何库中可能使用的任何类相同。

I can't seem to find EntityObjects property anywhere in EF6 documentation. 我似乎无法在EF6文档中的任何位置找到EntityObjects属性。 Are you sure you removed completely all references to EF4 from your project? 您确定从项目中完全删除了对EF4的所有引用吗?

Maybe could you also replace your code by this: 也许你也可以用这个代替你的代码:

EntityObject e = context.EntityObjects.FirstOrDefault();

And see what is the value of e ? 看看e的价值是什么? Finally, if you're trying to select all objects from a table in your database and put them in a List , isn't this statement an option? 最后,如果您尝试从数据库中的表中选择所有对象并将它们放在List ,那么这个语句不是一个选项吗?

var myObjects = (from s in context.tableName select s).ToList();

I had a somewhat similar problem, where each time I called ToListAsync() on a DbSet EF threw a NullReferenceException. 我有一个类似的问题,每次我在DbSet EF上调用ToListAsync()时都会抛出一个NullReferenceException。 For the sake of anyone who ends up here from Google (I couldn't find any help online), in my case it was a mixup from calling async code synchronously (a restriction of an attribute from a third party framework). 对于那些从谷歌来到这里的人来说(我在网上找不到任何帮助),在我的情况下,它是同步调用异步代码的混合(来自第三方框架的属性限制)。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM