C# 来自microsoft站点的实体框架教程

C# 来自microsoft站点的实体框架教程,c#,entity-framework,localdb,C#,Entity Framework,Localdb,我制作这个教程 我有相同的模型、上下文,我通过NuGet将实体框架添加到项目中。 我的主要职能是: static void Main(string[] args) { using (var db = new BloggingContext()) { // Create and save a new Blog Console.Write("Enter a name for a new Blog: "); var name = Cons

我制作这个教程 我有相同的模型、上下文,我通过NuGet将实体框架添加到项目中。 我的主要职能是:

static void Main(string[] args)
{
    using (var db = new BloggingContext())
    {
        // Create and save a new Blog
        Console.Write("Enter a name for a new Blog: ");
        var name = Console.ReadLine();

        var blog = new Blog { Name = name };
        db.Blogs.Add(blog);
        db.SaveChanges();

        // Display all Blogs from the database
        var query = from b in db.Blogs
                    orderby b.Name
                    select b;

        Console.WriteLine("All blogs in the database:");

        foreach (var item in query)      //here i get exception
        {
            Console.WriteLine(item.Name);
        }

        Console.WriteLine("Press any key to exit...");
        Console.ReadKey();
    }
}
在查询行中的foreach var项中,我得到以下异常:

System.Reflection.TargetInvocationException was unhandled
HResult=-2146232828
Message=Obiekt docelowy wywołania zgłosił wyjątek.
Source=mscorlib
StackTrace:
   w System.RuntimeMethodHandle.InvokeMethod(Object target, Object[] arguments, Signature sig, Boolean constructor)
   w System.Reflection.RuntimeMethodInfo.UnsafeInvokeInternal(Object obj, Object[] parameters, Object[] arguments)
   w System.Reflection.RuntimeMethodInfo.Invoke(Object obj, BindingFlags invokeAttr, Binder binder, Object[] parameters, CultureInfo culture)
   w System.Reflection.MethodBase.Invoke(Object obj, Object[] parameters)
   w 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)
   w 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)
   w System.Data.Entity.Core.Objects.ELinq.ELinqQueryState.GetExecutionPlan(Nullable`1 forMergeOption)
   w System.Data.Entity.Core.Objects.ObjectQuery`1.<>c__DisplayClassb.<GetResults>b__a()
   w System.Data.Entity.Core.Objects.ObjectContext.ExecuteInTransaction[T](Func`1 func, IDbExecutionStrategy executionStrategy, Boolean startLocalTransaction, Boolean releaseConnectionOnSuccess)
   w System.Data.Entity.Core.Objects.ObjectQuery`1.<>c__DisplayClassb.<GetResults>b__9()
   w System.Data.Entity.SqlServer.DefaultSqlExecutionStrategy.Execute[TResult](Func`1 operation)
   w System.Data.Entity.Core.Objects.ObjectQuery`1.GetResults(Nullable`1 forMergeOption)
   w System.Data.Entity.Core.Objects.ObjectQuery`1.<System.Collections.Generic.IEnumerable<T>.GetEnumerator>b__0()
   w System.Lazy`1.CreateValue()
   w System.Lazy`1.LazyInitValue()
   w System.Lazy`1.get_Value()
   w System.Data.Entity.Internal.LazyEnumerator`1.MoveNext()
   w ConsoleApplication1.Program.Main(String[] args) w c:\Users\Jakub_PC\Desktop\NTR\Lab2\ConsoleApplication1\ConsoleApplication1\Program.cs:wiersz 29
   w System.AppDomain._nExecuteAssembly(RuntimeAssembly assembly, String[] args)
   w System.AppDomain.ExecuteAssembly(String assemblyFile, Evidence assemblySecurity, String[] args)
   w Microsoft.VisualStudio.HostingProcess.HostProc.RunUsersAssembly()
   w System.Threading.ThreadHelper.ThreadStart_Context(Object state)
   w System.Threading.ExecutionContext.RunInternal(ExecutionContext executionContext, ContextCallback callback, Object state, Boolean preserveSyncCtx)
   w System.Threading.ExecutionContext.Run(ExecutionContext executionContext, ContextCallback callback, Object state, Boolean preserveSyncCtx)
   w System.Threading.ExecutionContext.Run(ExecutionContext executionContext, ContextCallback callback, Object state)
   w System.Threading.ThreadHelper.ThreadStart()
InnerException: System.TypeLoadException
   HResult=-2146233054
   Message=Odmowa dostępu: 'ConsoleApplication1.Program+Student'.
   Source=mscorlib
   TypeName=""
   StackTrace:
        w System.Reflection.Emit.TypeBuilder.TermCreateClass(RuntimeModule module, Int32 tk, ObjectHandleOnStack type)
        w System.Reflection.Emit.TypeBuilder.CreateTypeNoLock()
        w System.Reflection.Emit.TypeBuilder.CreateType()
        w System.Data.Entity.Core.Objects.Internal.EntityProxyFactory.ProxyTypeBuilder.CreateType(ModuleBuilder moduleBuilder)
        w System.Data.Entity.Core.Objects.Internal.EntityProxyFactory.BuildType(ModuleBuilder moduleBuilder, ClrEntityType ospaceEntityType, MetadataWorkspace workspace)
        w System.Data.Entity.Core.Objects.Internal.EntityProxyFactory.TryCreateProxyType(EntityType ospaceEntityType, MetadataWorkspace workspace)
        w System.Data.Entity.Core.Objects.Internal.EntityProxyFactory.GetProxyType(ClrEntityType ospaceEntityType, MetadataWorkspace workspace)
        w System.Data.Entity.Core.Common.Internal.Materialization.Translator.TranslatorVisitor.Visit(EntityColumnMap columnMap, TranslatorArg arg)
        w System.Data.Entity.Core.Query.InternalTrees.EntityColumnMap.Accept[TResultType,TArgType](ColumnMapVisitorWithResults`2 visitor, TArgType arg)
        w System.Data.Entity.Core.Common.Internal.Materialization.Translator.TranslatorVisitor.HandleSpandexRecord(RecordColumnMap columnMap, TranslatorArg arg, RowType spanRowType)
        w System.Data.Entity.Core.Common.Internal.Materialization.Translator.TranslatorVisitor.Visit(RecordColumnMap columnMap, TranslatorArg arg)
        w System.Data.Entity.Core.Query.InternalTrees.RecordColumnMap.Accept[TResultType,TArgType](ColumnMapVisitorWithResults`2 visitor, TArgType arg)
        w System.Data.Entity.Core.Common.Internal.Materialization.Translator.TranslatorVisitor.ProcessCollectionColumnMap(CollectionColumnMap columnMap, TranslatorArg arg, ColumnMap discriminatorColumnMap, Object discriminatorValue)
        w System.Data.Entity.Core.Common.Internal.Materialization.Translator.TranslatorVisitor.ProcessCollectionColumnMap(CollectionColumnMap columnMap, TranslatorArg arg)
        w System.Data.Entity.Core.Common.Internal.Materialization.Translator.TranslatorVisitor.Visit(SimpleCollectionColumnMap columnMap, TranslatorArg arg)
        w System.Data.Entity.Core.Query.InternalTrees.SimpleCollectionColumnMap.Accept[TResultType,TArgType](ColumnMapVisitorWithResults`2 visitor, TArgType arg)
        w System.Data.Entity.Core.Common.Internal.Materialization.Translator.TranslateColumnMap[T](ColumnMap columnMap, MetadataWorkspace workspace, SpanIndex spanIndex, MergeOption mergeOption, Boolean streaming, Boolean valueLayer) 
出什么事了?哪里有问题?我想用Visual Studio 2012安装localDb

更新:


我做了一个新项目,又重新做了一个教程。一切都好,我现在没有任何例外。我不知道为什么

请确保包含db.Blogs的数据库存在,否则您无法从查询中获得任何信息。

如果数据库不存在,我想您会错过:

System.Data.Entity.Database.SetInitializer<BloggingContext>(new DropCreateDatabaseIfModelChanges<BloggingContext>());
将上述代码添加到Global.asax文件中的App_Start方法


这篇文章对你很有用

我认为它不存在,但我如何创建它呢?