虚拟列表<T>:“函数评估需要所有线程运行”

4
我正在按照以下教程学习快速编码。 Code First to a New Database 我已经完成了该教程的第4步,但当我尝试运行我的代码时出现了问题。我在以下代码中遇到了以下异常...
    foreach (var item in query)
    {
        Console.WriteLine(item.Name);
    }
    {"Exception has been thrown by the target of an invocation."}

带有内部异常

    {"Access is denied: 'CodeFastNewDatabase.Program+Blog'.":""}

当我尝试检查db变量属性时,很多都有调试错误提示:“函数评估需要运行所有线程”。该代码正在我的本地数据库中创建数据库并插入值。
如果我删除类Blog和Post中的属性的虚拟限定符,则可以解决此问题。
    public virtual List<Post> Posts { get; set; }
    public virtual Blog Blog { get; set; }

我在其他项目中也遇到同样的异常。许多属性显示“函数评估需要运行所有线程”。
我正在使用Entity Framework 6.0。
编辑:
Blog是DbContext对象的属性,我在程序类的主函数中初始化了它。然后将博客添加到上下文中,并保存它。这将创建/更新数据库并插入给定的值。代码与示例链接中的相同。
[堆栈跟踪] 以下是我捕获的堆栈跟踪。
   at System.Environment.GetStackTrace(Exception e, Boolean needFileInfo)
   at System.Environment.get_StackTrace()
   at CodeFastNewDatabase.Program.Main(String[] args) in f:\Dropbox\Projects\visual studio 2012\Projects\CodeFastNewDatabase\CodeFastNewDatabase\Program.cs:line 32
   at System.AppDomain._nExecuteAssembly(RuntimeAssembly assembly, String[] args)
   at System.AppDomain.ExecuteAssembly(String assemblyFile, Evidence assemblySecurity, String[] args)
   at Microsoft.VisualStudio.HostingProcess.HostProc.RunUsersAssembly()
   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()

以下是两个异常(外部和内部)的堆栈跟踪:

    at System.RuntimeMethodHandle.InvokeMethod(Object target, Object[] arguments, Signature sig, Boolean constructor)
    at System.Reflection.RuntimeMethodInfo.UnsafeInvokeInternal(Object obj, Object[] parameters, Object[] arguments)
    at System.Reflection.RuntimeMethodInfo.Invoke(Object obj, BindingFlags invokeAttr, Binder binder, Object[] parameters, CultureInfo culture)
    at System.Reflection.MethodBase.Invoke(Object obj, Object[] parameters)
    at System.Data.Entity.Core.Common.Internal.Materialization.Translator.TranslateColumnMap(Translator translator, Type elementType, ColumnMap columnMap, MetadataWorkspace workspace, SpanIndex spanIndex, MergeOption mergeOption, Boolean streaming, Boolean valueLayer)
    at System.Data.Entity.Core.Objects.Internal.ObjectQueryExecutionPlanFactory.Prepare(ObjectContext context, DbQueryCommandTree tree, Type elementType, MergeOption mergeOption, Boolean streaming, Span span, IEnumerable`1 compiledQueryParameters, AliasGenerator aliasGenerator)
    at System.Data.Entity.Core.Objects.ELinq.ELinqQueryState.GetExecutionPlan(Nullable`1 forMergeOption)
    at System.Data.Entity.Core.Objects.ObjectQuery`1.<>c__DisplayClassb.<GetResults>b__a()
    at System.Data.Entity.Core.Objects.ObjectContext.ExecuteInTransaction[T](Func`1 func, IDbExecutionStrategy executionStrategy, Boolean startLocalTransaction, Boolean releaseConnectionOnSuccess)
    at System.Data.Entity.Core.Objects.ObjectQuery`1.<>c__DisplayClassb.<GetResults>b__9()
    at System.Data.Entity.SqlServer.DefaultSqlExecutionStrategy.Execute[TResult](Func`1 operation)
    at System.Data.Entity.Core.Objects.ObjectQuery`1.GetResults(Nullable`1 forMergeOption)
    at System.Data.Entity.Core.Objects.ObjectQuery`1.<System.Collections.Generic.IEnumerable<T>.GetEnumerator>b__0()
    at System.Lazy`1.CreateValue()
    at System.Lazy`1.LazyInitValue()
    at System.Lazy`1.get_Value()
    at System.Data.Entity.Internal.LazyEnumerator`1.MoveNext()
    at CodeFastNewDatabase.Program.Main(String[] args) in f:\Dropbox\Projects\visual studio 2012\Projects\CodeFastNewDatabase\CodeFastNewDatabase\Program.cs:line 33
    at System.AppDomain._nExecuteAssembly(RuntimeAssembly assembly, String[] args)
    at System.AppDomain.ExecuteAssembly(String assemblyFile, Evidence assemblySecurity, String[] args)
    at Microsoft.VisualStudio.HostingProcess.HostProc.RunUsersAssembly()
    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()

内部异常堆栈跟踪

    at System.Reflection.Emit.TypeBuilder.TermCreateClass(RuntimeModule module, Int32 tk, ObjectHandleOnStack type)
    at System.Reflection.Emit.TypeBuilder.CreateTypeNoLock()
    at System.Reflection.Emit.TypeBuilder.CreateType()
    at System.Data.Entity.Core.Objects.Internal.EntityProxyFactory.ProxyTypeBuilder.CreateType(ModuleBuilder moduleBuilder)
    at System.Data.Entity.Core.Objects.Internal.EntityProxyFactory.BuildType(ModuleBuilder moduleBuilder, ClrEntityType ospaceEntityType, MetadataWorkspace workspace)
    at System.Data.Entity.Core.Objects.Internal.EntityProxyFactory.TryCreateProxyType(EntityType ospaceEntityType, MetadataWorkspace workspace)
    at System.Data.Entity.Core.Objects.Internal.EntityProxyFactory.GetProxyType(ClrEntityType ospaceEntityType, MetadataWorkspace workspace)
    at System.Data.Entity.Core.Common.Internal.Materialization.Translator.TranslatorVisitor.Visit(EntityColumnMap columnMap, TranslatorArg arg)
    at System.Data.Entity.Core.Query.InternalTrees.EntityColumnMap.Accept[TResultType,TArgType](ColumnMapVisitorWithResults`2 visitor, TArgType arg)
    at System.Data.Entity.Core.Common.Internal.Materialization.Translator.TranslatorVisitor.ProcessCollectionColumnMap(CollectionColumnMap columnMap, TranslatorArg arg, ColumnMap discriminatorColumnMap, Object discriminatorValue)
    at System.Data.Entity.Core.Common.Internal.Materialization.Translator.TranslatorVisitor.ProcessCollectionColumnMap(CollectionColumnMap columnMap, TranslatorArg arg)
    at System.Data.Entity.Core.Common.Internal.Materialization.Translator.TranslatorVisitor.Visit(SimpleCollectionColumnMap columnMap, TranslatorArg arg)
    at System.Data.Entity.Core.Query.InternalTrees.SimpleCollectionColumnMap.Accept[TResultType,TArgType](ColumnMapVisitorWithResults`2 visitor, TArgType arg)
    at System.Data.Entity.Core.Common.Internal.Materialization.Translator.TranslateColumnMap[T](ColumnMap columnMap, MetadataWorkspace workspace, SpanIndex spanIndex, MergeOption mergeOption, Boolean streaming, Boolean valueLayer)

你如何声明你的 Blog 类型?并能否发布完整的堆栈跟踪? - Jon Skeet
这不是一个有用的堆栈跟踪 - 它只是显示您调用 Environment.StackTrace。异常应该已经包含了完整的细节。 - Jon Skeet
@JonSkeet 按照你的要求,更新了帖子,其中包括外部异常System.Reflection.TargetInvocationException和内部异常System.TypeLoadException。 - spyronum
1
代码示例中说要将 BlogPost 放在 Program 声明的下方 - 但看起来你把它们放在了 Program 的声明内部。我不知道这是否相关,但可能是这样。 - Jon Skeet
是的!!! 就是这样。我只是把代码从程序类中拿出来,它就简单地工作了。而且新创建的数据库也没有任何无效字符 :)非常感谢你,伙计。这非常有帮助。 - spyronum
显示剩余2条评论
3个回答

2
异常消息显示您已将BlogPost用作Program内嵌类,而说明如下:

在Program.cs中的Program类定义下面添加以下两个类。

个人认为应将它们放入单独的文件中,但这是另一回事。考虑到它们是公共类,我仍然很惊讶它失败了,但听起来那就是问题所在。
至于“函数评估要求所有线程运行”-这实际上不是一个错误,它只是显示了在评估属性时需要使用各种线程的调试的限制。

好的,我遇到了一个新问题,不确定是否应该为此创建一个新问题,只是想先向你们请教一下。 我尝试使用 using(var db = new Context()) 来创建 DbContext 的实例,问题是它只创建了数据库一次,之后当我删除数据库再次测试时,它就无法重新创建数据库。你们有任何想法为什么会出现这种情况吗? 编辑: 算了,我刚刚调用了 Database.CreateIfNotExists();,这解决了我的问题。 感谢大家的努力 :) - spyronum

1
你提供的代码是针对 Entity Framework 5 编写的。在 Entity Framework 6 中,虚拟代理对象使用实现了 Lazy<T> 的方法进行延迟加载,为了线程安全,需要进行不同的处理。我的建议是,在 EF6 中使用 virtual ICollection<Post> 而不是 virtual List<Post>,或者回退到 EF5,因为你所参考的教程是针对 EF5 设计的。

问题在EF5和EF6中仍然存在。将其更改为ICollection也无法修复错误。 - spyronum

0
对我来说问题在于,我的 Repository 返回了一个 IQueryable<T>,但是在我的 Service 方法中忘记使用 ToList() 方法来处理返回的结果了。

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接