简体   繁体   中英

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.

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:

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

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:

    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.

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.

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.

I can't seem to find EntityObjects property anywhere in EF6 documentation. Are you sure you removed completely all references to EF4 from your project?

Maybe could you also replace your code by this:

EntityObject e = context.EntityObjects.FirstOrDefault();

And see what is the value of 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?

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. 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).

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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