38

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 don't 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:

spottedmahn
  • 14,823
  • 13
  • 108
  • 178
Kirsten
  • 15,730
  • 41
  • 179
  • 318
  • Do you by any chance see this exception when debugging the application but you do not see it when running the app without the debugger attached? – Pawel Jan 02 '14 at 23:32
  • That is correct. I updated the question with the information. – Kirsten Jan 02 '14 at 23:57
  • Useful link for anyone having a simlar issue https://forums.asp.net/t/2133118.aspx?How+to+ignore+or+stop+creating+table+from+class+EF+code+first – Phil3992 Apr 04 '18 at 13:31

6 Answers6

79

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.

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.

Pawel
  • 31,342
  • 4
  • 73
  • 104
  • 2
    thanks, i will check. I dont have a Migrations folder in the project - so it is confusing as to why it is trying to make the table. – Kirsten Jan 03 '14 at 22:38
  • @Pawel, I can't find that option in VS 2017 (15.3) – Shimmy Weitzhandler Sep 10 '17 at 16:00
  • @Shimmy - In VS 2017 you need open exception settings with Ctrl+Alt+E or go to Debug->Windows->Exception Settings. Right click on Common Language Runtime Exceptions and select Restore Defaults. – Pawel Sep 11 '17 at 05:00
  • @Pawel is there a way to disable "thrown" exceptions? This is so annoying. – Shimmy Weitzhandler Sep 11 '17 at 12:01
  • 1
    As I said in my comment - right click on `Common Language Runtime Exceptions` and select `Restore Defaults`. This will disable breaking when exceptions are thrown but handled. The debugger will still break for exceptions that are thrown but not handled. – Pawel Sep 11 '17 at 16:56
  • @Pawel, I missed that, sorry and I appreciate your patience emphasizing that again. – Shimmy Weitzhandler Sep 16 '17 at 18:05
  • Great and simple answer. All issues are just gone now. Just out of curisity, can you specifications for when a specific exception does or doesn't stop when handled? – Shimmy Weitzhandler Sep 16 '17 at 18:10
  • If an exception is thrown and handled it will not break unless you change exception settings. If the exception is not handled it will break in the debugger regardless of the settings. Unhandled exceptions cause in general application crashes. – Pawel Sep 17 '17 at 20:18
  • +1 for explaining the case that the database was not created with EF migrations. I used Entity Framework Powertools Beta 4, Reverse Engineer Code First, on an existing database. In that case, no __MigrationHistory table is created. I didn't realize I was looking at an EF-internally handled error before reading this answer. – R. Schreurs Oct 26 '17 at 08:48
  • Wondering if there is a way to override EF check for __MigrationsHistory, because I would love to make an OBJECT_ID check before everything so no exception is thrown unless really needed. Thank you for your answer BTW! +1 – Zéiksz Feb 20 '18 at 13:37
  • I don't think you can override the check but the exception only bubbles up in VS. You can mute this exception (because it is handled by EF) and it should not mute actual exceptions that are not being handled. – Pawel Feb 20 '18 at 22:34
  • 1
    This is a "System.Data.SqlClient.SqlException" type of Exception. If we disable this from exception settings, aren't we going to lose all our defined SqlException code? – Teoman shipahi Mar 30 '18 at 15:09
  • I don't quite understand _to lose all our defined SqlException code_. You are not changing any code you are telling the tool to not show exceptions that are being handled and don't reach your code when you're debugging. That's all. – Pawel Mar 30 '18 at 17:02
  • 2
    Thanx for this information, this was usefull, because application insights is still monitoring this exception – Christian van R Jan 07 '20 at 18:41
  • 1
    Thanks, one of our devs got crazy about this not working on this machine. – Wiktor Zychla May 15 '20 at 08:48
19

You can turn off code first database initialization for your database, by adding this to your context's constructor:

System.Data.Entity.Database.SetInitializer<YourContext>(null);

This should prevent the attempt to access dbo.__MigrationHistory.

Danny Varod
  • 17,324
  • 5
  • 69
  • 111
1

I faced the same issue. It means that EF is not able to find the __Migration history table. also note for some reason it has to be dbo.__MigrationHistory (note dbo). Ensure that you have run "update-database" atleast once before running the Context

Rishabh Jain
  • 518
  • 6
  • 11
0

I forgot to add the database name in my connection string. After I added, it started to work

Charlie
  • 4,827
  • 2
  • 31
  • 55
0

Just uncheck break checkbox then click enable editing to proceed

enter image description here

TAHA SULTAN TEMURI
  • 4,031
  • 2
  • 40
  • 66
0

the database I was using Table __MigrationHistory was missing, so when I Scripted migrations, it generated this code:

IF OBJECT_ID(N'[__EFMigrationsHistory]') IS NULL
BEGIN
    CREATE TABLE [__EFMigrationsHistory] (
        [MigrationId] nvarchar(150) NOT NULL,
        [ProductVersion] nvarchar(32) NOT NULL,
        CONSTRAINT [PK___EFMigrationsHistory] PRIMARY KEY ([MigrationId])
    );
END;

and This fixed..

Zakarie Abdallah
  • 342
  • 1
  • 6
  • 10