使用 Database.Create 的对象名称“dbo.__MigrationHistory"无效;传入连接字符串时的EF6.02 [英] Invalid object name 'dbo.__MigrationHistory' using Database.Create; EF6.02 when connection string is passed in

查看:16
本文介绍了使用 Database.Create 的对象名称“dbo.__MigrationHistory"无效;传入连接字符串时的EF6.02的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在尝试使用以下代码创建数据库时遇到错误.请注意,如果未传入连接字符串,则不会发生此问题.当我在 IDE 中运行程序时也会出现问题.如果我运行程序 .exe 或在 IDE 中运行单元测试,则不会发生这种情况.

I experience an error when trying to create a database using the following code. Note the problem does not happen if the connection string is not passed in. Also the problem happens when I run the program in the IDE. It does not happen if I run the program .exe or if I run the unit tests within the IDE.

但是,如果数据库是通过运行单元测试或运行 .EXE 创建的,那么 __MigrationHistory 表将在主表部分创建,而不是系统表.

However if the database is created by running the unit tests or by running the .EXE then the __MigrationHistory table is created in the main tables section, not the system tables.

public Context(string connString, bool AddInitialRecords )
    : base(connString ?? "MyContextName")
{
    this.CheckDatabase(AddInitialRecords);
}

public void CheckDatabase(bool AddInitialRecords)
{
    if (this.Database.Exists())
    {
         // upgrade stuff
    }
    else
    {
       Database.Create();  // error occurs here
        // seeding stuff 
    }
}

如果我只使用类似的东西,我不会遇到问题

I don't get the problem if I just use something like

var db1 = new Context();
db1.Database.CreateIfNotExists();

我在 here 找到了一些文档,但这让我很困惑.我是从稳定版本"安装的,我肯定没有经历过 2012 年的事情吗?我对 PM 做错了什么?

I have found some documentation here but it confuses me. I am installing from a "stable build" surely I aren't experiencing something from 2012? What could I be doing wrong with PM?

问题的错误信息是......

The error message for the problem is....

发生 System.Data.Entity.Core.EntityCommandExecutionException
HResult=-2146232004 消息=执行命令定义.有关详细信息,请参阅内部异常.
来源=EntityFramework StackTrace:在 System.Data.Entity.Core.EntityClient.Internal.EntityCommandDefinition.ExecuteStoreCommands(EntityCommandentityCommand,CommandBehavior 行为)InnerException:System.Data.SqlClient.SqlExceptionH结果=-2146232060消息=无效的对象名称 'dbo.__MigrationHistory'.Source=.Net SqlClient 数据提供者错误代码=-2146232060班级=16行号=1数量=208程序=""服务器=.SQLEXPRESS状态=1堆栈跟踪:在 System.Data.SqlClient.SqlConnection.OnError(SqlException 异常,Boolean breakConnection, Action`1 wrapCloseInAction)在 System.Data.SqlClient.TdsParser.ThrowExceptionAndWarning(TdsParserStateObjectstateObj, Boolean callerHasConnectionLock, Boolean asyncClose)在 System.Data.SqlClient.TdsParser.TryRun(RunBehavior runBehavior,SqlCommand cmdHandler,SqlDataReader 数据流,BulkCopySimpleResultSet bulkCopyHandler, TdsParserStateObjectstateObj, Boolean &数据就绪)在 System.Data.SqlClient.SqlDataReader.TryConsumeMetaData()在 System.Data.SqlClient.SqlDataReader.get_MetaData()在 System.Data.SqlClient.SqlCommand.FinishExecuteReader(SqlDataReader ds,RunBehavior runBehavior,字符串 resetOptionsString)在 System.Data.SqlClient.SqlCommand.RunExecuteReaderTds(CommandBehaviorcmdBehavior、RunBehavior runBehavior、布尔 returnStream、布尔异步,Int32 超时,任务&任务,布尔 asyncWrite)在 System.Data.SqlClient.SqlCommand.RunExecuteReader(CommandBehaviorcmdBehavior、RunBehavior、runBehavior、布尔返回流、字符串方法,TaskCompletionSource`1 完成,Int32 超时,Task&任务,布尔异步写入)在 System.Data.SqlClient.SqlCommand.RunExecuteReader(CommandBehaviorcmdBehavior、RunBehavior、runBehavior、布尔返回流、字符串方法)在 System.Data.SqlClient.SqlCommand.ExecuteReader(CommandBehavior行为,字符串方法)在 System.Data.SqlClient.SqlCommand.ExecuteDbDataReader(CommandBehavior行为)在 System.Data.Entity.Infrastructure.Interception.DbCommandDispatcher.<>c__DisplayClassb.b__8()在 System.Data.Entity.Infrastructure.Interception.InternalDispatcher`1.Dispatch[TInterceptionContext,TResult](Func`1操作,TInterceptionContext,interceptionContext,Action`1正在执行,Action`1 已执行)在 System.Data.Entity.Infrastructure.Interception.DbCommandDispatcher.Reader(DbCommand命令,DbCommandInterceptionContext 拦截上下文)在 System.Data.Entity.Internal.InterceptableDbCommand.ExecuteDbDataReader(CommandBehavior行为)在 System.Data.Entity.Core.EntityClient.Internal.EntityCommandDefinition.ExecuteStoreCommands(EntityCommandentityCommand、CommandBehavior 行为)内部异常:

System.Data.Entity.Core.EntityCommandExecutionException occurred
HResult=-2146232004 Message=An error occurred while executing the command definition. See the inner exception for details.
Source=EntityFramework StackTrace: at System.Data.Entity.Core.EntityClient.Internal.EntityCommandDefinition.ExecuteStoreCommands(EntityCommand entityCommand, CommandBehavior behavior) InnerException: System.Data.SqlClient.SqlException HResult=-2146232060 Message=Invalid object name 'dbo.__MigrationHistory'. Source=.Net SqlClient Data Provider ErrorCode=-2146232060 Class=16 LineNumber=1 Number=208 Procedure="" Server=.SQLEXPRESS State=1 StackTrace: at System.Data.SqlClient.SqlConnection.OnError(SqlException exception, Boolean breakConnection, Action`1 wrapCloseInAction) at System.Data.SqlClient.TdsParser.ThrowExceptionAndWarning(TdsParserStateObject stateObj, Boolean callerHasConnectionLock, Boolean asyncClose) at System.Data.SqlClient.TdsParser.TryRun(RunBehavior runBehavior, SqlCommand cmdHandler, SqlDataReader dataStream, BulkCopySimpleResultSet bulkCopyHandler, TdsParserStateObject stateObj, Boolean& dataReady) at System.Data.SqlClient.SqlDataReader.TryConsumeMetaData() at System.Data.SqlClient.SqlDataReader.get_MetaData() at System.Data.SqlClient.SqlCommand.FinishExecuteReader(SqlDataReader ds, RunBehavior runBehavior, String resetOptionsString) at System.Data.SqlClient.SqlCommand.RunExecuteReaderTds(CommandBehavior cmdBehavior, RunBehavior runBehavior, Boolean returnStream, Boolean async, Int32 timeout, Task& task, Boolean asyncWrite) at System.Data.SqlClient.SqlCommand.RunExecuteReader(CommandBehavior cmdBehavior, RunBehavior runBehavior, Boolean returnStream, String method, TaskCompletionSource`1 completion, Int32 timeout, Task& task, Boolean asyncWrite) at System.Data.SqlClient.SqlCommand.RunExecuteReader(CommandBehavior cmdBehavior, RunBehavior runBehavior, Boolean returnStream, String method) at System.Data.SqlClient.SqlCommand.ExecuteReader(CommandBehavior behavior, String method) at System.Data.SqlClient.SqlCommand.ExecuteDbDataReader(CommandBehavior behavior) at System.Data.Entity.Infrastructure.Interception.DbCommandDispatcher.<>c__DisplayClassb.b__8() at System.Data.Entity.Infrastructure.Interception.InternalDispatcher`1.Dispatch[TInterceptionContext,TResult](Func`1 operation, TInterceptionContext interceptionContext, Action`1 executing, Action`1 executed) at System.Data.Entity.Infrastructure.Interception.DbCommandDispatcher.Reader(DbCommand command, DbCommandInterceptionContext interceptionContext) at System.Data.Entity.Internal.InterceptableDbCommand.ExecuteDbDataReader(CommandBehavior behavior) at System.Data.Entity.Core.EntityClient.Internal.EntityCommandDefinition.ExecuteStoreCommands(EntityCommand entityCommand, CommandBehavior behavior) InnerException:

推荐答案

发生这种情况是因为 EF 对 __MigrationsHistory 表进行了一些探测.例如,您可以将 EF 与不是使用 EF 迁移创建的现有数据库一起使用,但 EF 无法知道它,因此它会尝试连接到数据库并使用表来检查这一点.如果表不存在,则会抛出异常.然后 EF 捕获异常并做正确的事情(例如,如果需要,创建 __MigrationsHistory 表,或者在不使用迁移的情况下继续).

This happens because EF does some probing for the __MigrationsHistory table. For instance you can use EF with an existing database that was not created using EF Migrations but EF has no way of knowing it so it tries to connect to the database and uses the table to check this. If the table does not exist an exception will be thrown. EF then catches the exception and does the right thing (e.g. creates the __MigrationsHistory table if needed or proceeds without using migrations).

一般来说,在没有调试器的情况下运行时您不会看到此异常.但是,当调试您的代码AND时,如果设置了在抛出异常时中断执行的选项,您将看到所有正在抛出的异常,即使它们是在内部处理的并且永远不会到达您的代码.默认设置是在抛出异常时不中断,而仅在抛出未处理的异常时才中断.您可以通过选中/取消选中 Debug -> Exceptions 对话框中Thrown"列中的复选框来更改设置.

In general you won't see this exception when running without the debugger. However when debugging your code AND when the option to break the execution when an exception is thrown is set you will see all the exceptions that are being thrown even if they are internally handled and never reach your code. The default setting is not to break when the exception is thrown but only when an exception that is not being handled is thrown. You can change the setting by checking/unchecking a check box in the "Thrown" column in the Debug -> Exceptions dialog.

在 VS 2017 中,您可以使用 Debug->Windows->Exception Settings 打开异常设置.如果您右键单击公共语言运行时异常",您可以选择恢复默认值",这会在大多数异常被抛出时禁用您的程序.

In VS 2017 you open exception settings using Debug->Windows->Exception Settings. If you right-click on the "Common Language Runtime Exceptions" you can select the "Restore Defaults" which disables breaking your program when most of the exceptions are thrown.

这篇关于使用 Database.Create 的对象名称“dbo.__MigrationHistory"无效;传入连接字符串时的EF6.02的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆