从EF4升级后在EF6中查询数据

本文关键字:EF6 查询 数据 EF4 | 更新日期: 2023-09-27 18:16:35

我在从实体框架上下文中获取数据时遇到了一些麻烦。我正在将我的应用程序从实体框架4升级到6,它还没有参加派对。

现在,如果我试图从我的数据库查询任何记录,我得到一个空引用异常。

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

第一行运行没有错误。第二行抛出一个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

我现在关闭的猜测是,有一个问题,我的连接字符串阻止上下文与数据库连接,所以这里是我的配置文件:

<?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>

我遗漏了什么吗?会是别的什么吗?

连接字符串是坏的,但即使在修复它之后,我得到完全相同的错误。我可以打开到数据库的连接,但是当我试图查看上下文中的任何集合时,它会抛出空引用异常。

这是非常令人沮丧的

另一个更新

我没有看到太多的帮助,所以我张贴了一些我找到的信息。

我找到了实体框架源,这是崩溃的方法:

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

这是前面调用方法的代码块:

        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;
            }
        }

注意它检查cspaceType。

我用相同的实体模型创建了一个新的项目,它工作得很好,所以它与我的特定设置或项目或其他东西有关。

从EF4升级后在EF6中查询数据

当我发布这篇文章时,我有一个糟糕的连接字符串,所以要小心,但这实际上不是问题

问题是名称冲突。我在实体框架中的一个类与我在其他引用中的一个类具有相同的名称。

所以,作为一般做法,我建议给你的每个实体框架类一个前缀,以绝对确保它永远不会像你可能在任何库中使用的任何类一样。

我似乎无法在EF6文档的任何地方找到EntityObjects属性。你确定你从你的项目中完全删除了所有对EF4的引用吗?

也许你也可以这样替换你的代码:

EntityObject e = context.EntityObjects.FirstOrDefault();

看看e的值是多少?最后,如果您试图从数据库中的表中选择所有对象并将它们放在List中,这不是一个选项吗?

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

我有一个类似的问题,每次我在DbSet上调用ToListAsync()时,EF都会抛出一个NullReferenceException。对于任何从谷歌结束的人(我在网上找不到任何帮助),在我的情况下,这是同步调用异步代码的混淆(来自第三方框架的属性限制)。