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

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

问题描述

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



但是,如果数据库是通过运行单元测试或运行.EXE,然后在主表部分中创建___MigrationHistory表,而不是系统表。

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

public void CheckDatabase(bool AddInitialRecords)
{
if(this.Database.Exists())
{
//升级资料
}
else
{
Database.Create(); //错误发生在这里
//播种东西
}

我不会得到如果我只是使用类似

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

我已经找到一些文档这里,但它困惑我。我从一个稳定的建设安装,肯定我没有体验到2012年的东西?我可以做什么错误的PM?



该问题的错误消息是....


System.Data.Entity.Core.EntityCommandExecutionException发生

HResult = -2146232004 Message =执行
命令定义时发生错误。查看内部异常的详细信息。

Source = EntityFramework StackTrace:
在System.Data.Entity.Core.EntityClient.Internal.EntityCommandDefinition.ExecuteStoreCommands(EntityCommand
entityCommand,CommandBehavior行为) InnerException:
System.Data.SqlClient.SqlException
HResult = -2146232060
Message =无效的对象名称'dbo .__ MigrationHistory'。
Source = .Net SqlClient数据提供者
ErrorCode = -2146232060
Class = 16
LineNumber = 1
Number = 208
Procedure =
Server = .\SQLEXPRESS
State = 1
StackTrace:
在System.Data.SqlClient.SqlConnection.OnError(SqlException异常,
Boolean breakConnection,Action`1 wrapCloseInAction )
在System.Data.SqlClient.TdsParser.ThrowExceptionAndWarning(TdsParserStateObject
stateObj,Boolean callerHasConnectionLock,Boolean asyncClose)
在System.Data.SqlClient.TdsParser.TryRun(RunBehavior runBehavior,SqlCommand cmdHandler, SqlDataReader dataStream,
BulkCopySimpleResultSet bulkCopyHandler,TdsParserStateObject
stateObj,Boolean& dataReady)
在System.Data.SqlClient.SqlDataReader.TryConsumeMetaData()
在System.Data.SqlClient.SqlDataReader。 get_MetaData()
在System.Data.SqlClient.SqlCommand.FinishExecuteReader(SqlDataReader ds,
RunBehavior runBehavior,String resetOptionsString)
在System.Data.SqlClient.SqlCommand.RunExecuteReaderTds(CommandBehavior
cmdBehavior,RunBehavior runBehavior,Boolean returnStream,Boolean
async,Int32 timeout,Task&任务,Boolean asyncWrite)
在System.Data.SqlClient.SqlCommand.RunExecuteReader(CommandBehavior
cmdBehavior,RunBehavior runBehavior,Boolean returnStream,String
方法,TaskCompletionSource`1完成,Int32超时,任务&任务,
Boolean asyncWrite)
在System.Data.SqlClient.SqlCommand.RunExecuteReader(CommandBehavior
cmdBehavior,RunBehavior runBehavior,Boolean returnStream,String
方法)
在系统.Data.SqlClient.SqlCommand.ExecuteReader(CommandBehavior
behavior,String方法)
在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拦截ionContext,Action`1
执行,Action`1执行)
在System.Data.Entity.Infrastructure.Interception.DbCommandDispatcher.Reader(DbCommand
命令,DbCommandInterceptionContext interceptionContext)
在(System.Data.Entity.Internal.InterceptableDbCommand.ExecuteDbDataReader
InnerException:



解决方案

这是因为EF对__MigrationsHistory表进行了一些探测。例如,您可以使用EF与不是使用EF迁移创建的现有数据库,但EF无法知道它,因此它尝试连接到数据库并使用该表来检查。如果表不存在将抛出异常。 EF然后捕获异常并执行正确的操作(例如,如果需要,可以创建__MigrationsHistory表,或者在不使用迁移的情况下进行)。一般来说,在没有调试器的情况下运行时,您将看不到此异常。但是,当调用您的代码 AND 时,如果在抛出异常时中断执行的选项设置,即使内部处理并且永远不会覆盖您的代码,您将看到所有被抛出的异常。抛出异常时,默认设置不会中断,但是仅当抛出未处理的异常时。您可以通过在调试 - >例外对话框中的抛出列中选中/取消选中复选框来更改设置。


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.

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 dont get the problem if I just use something like

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

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

解决方案

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

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

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