How to create a LocalDB instance for NEventStore - localdb

I'm trying to use LocalDb with NEventStore but, even though I think I have set-up the database correctly, I keep getting the following exception:
NEventStore.Persistence.StorageUnavailableException: Invalid object name 'Snapshots'.
In code I configure NEventStore to use the database like this:
this.EventStore = Wireup.Init()
.LogToOutputWindow()
.UsingInMemoryPersistence()
.UsingSqlPersistence("DefaultConnection")
.WithDialect(new MsSqlDialect())
.UsingJsonSerialization()
.LogToOutputWindow()
.Build();
I have the following database connection in my web.config file:
<add name="DefaultConnection" connectionString="Data Source=(LocalDb)\MSSQLLocalDB;AttachDbFilename=|DataDirectory|\MyDatabase.mdf;Initial Catalog=MyDatabase;Integrated Security=True" providerName="System.Data.SqlClient" />
And using Visual Studio I've added an SqlServerDatabase (MyDatabase.mdf) to the App_Data folder of my Asp.net MVC 5 project. NEventStore seems to be able to open the database (if I remove MyDatabase.mdf from my project I get a different exception). But it seems its unable to initialize the database correctly. When I browse the database, after running into the error message, I see that no tables have been created.
What makes this extra strange is that, if this document is correct, Snapshots should be the second table made. So it seems it has no problem creating the first one.
The complete stack trace for the StorageUnavailableException
at NEventStore.Persistence.Sql.SqlDialects.PagedEnumerationCollection.OpenNextPage() in c:\TeamCity\buildAgent\work\38b1777f2112a252\src\NEventStore\Persistence\Sql\SqlDialects\PagedEnumerationCollection.cs:line 200
at NEventStore.Persistence.Sql.SqlDialects.PagedEnumerationCollection.MoveToNextRecord() in c:\TeamCity\buildAgent\work\38b1777f2112a252\src\NEventStore\Persistence\Sql\SqlDialects\PagedEnumerationCollection.cs:line 146
at NEventStore.Persistence.Sql.SqlDialects.PagedEnumerationCollection.System.Collections.IEnumerator.MoveNext() in c:\TeamCity\buildAgent\work\38b1777f2112a252\src\NEventStore\Persistence\Sql\SqlDialects\PagedEnumerationCollection.cs:line 70
at System.Linq.Enumerable.WhereSelectEnumerableIterator`2.MoveNext()
at System.Linq.Enumerable.FirstOrDefault[TSource](IEnumerable`1 source)
at NEventStore.Persistence.Sql.SqlPersistenceEngine.GetSnapshot(String bucketId, String streamId, Int32 maxRevision) in c:\TeamCity\buildAgent\work\38b1777f2112a252\src\NEventStore\Persistence\Sql\SqlPersistenceEngine.cs:line 225
at NEventStore.Persistence.PipelineHooksAwarePersistanceDecorator.GetSnapshot(String bucketId, String streamId, Int32 maxRevision) in c:\TeamCity\buildAgent\work\38b1777f2112a252\src\NEventStore\Persistence\PipelineHooksAwarePersistanceDecorator.cs:line 45
at NEventStore.AccessSnapshotsExtensions.GetSnapshot(IAccessSnapshots accessSnapshots, String bucketId, Guid streamId, Int32 maxRevision) in c:\TeamCity\buildAgent\work\38b1777f2112a252\src\NEventStore\AccessSnapshotsExtensions.cs:line 49
at CommonDomain.Persistence.EventStore.EventStoreRepository.GetSnapshot(String bucketId, Guid id, Int32 version) in c:\TeamCity\buildAgent\work\38b1777f2112a252\src\NEventStore\CommonDomain\Persistence\EventStore\EventStoreRepository.cs:line 147
at CommonDomain.Persistence.EventStore.EventStoreRepository.GetById[TAggregate](String bucketId, Guid id, Int32 versionToLoad) in c:\TeamCity\buildAgent\work\38b1777f2112a252\src\NEventStore\CommonDomain\Persistence\EventStore\EventStoreRepository.cs:line 54
at CommonDomain.Persistence.EventStore.EventStoreRepository.GetById[TAggregate](Guid id, Int32 versionToLoad) in c:\TeamCity\buildAgent\work\38b1777f2112a252\src\NEventStore\CommonDomain\Persistence\EventStore\EventStoreRepository.cs:line 44
at CapraLibraShop.DataModel.Repositories.UserAggregateRepository.UserWithEmailExists(EmailAddress emailAddress) in D:\Projects\C#\CapraLibraShop\CapraLibraShop.DataModel\Repositories\UserAggregateRepository.cs:line 22
at CapraLibraShop.Controllers.AccountController.Register() in D:\Projects\C#\CapraLibraShop\CapraLibraShop\Controllers\AccountController.cs:line 55
at lambda_method(Closure , ControllerBase , Object[] )
at System.Web.Mvc.ActionMethodDispatcher.Execute(ControllerBase controller, Object[] parameters)
at System.Web.Mvc.ReflectedActionDescriptor.Execute(ControllerContext controllerContext, IDictionary`2 parameters)
at System.Web.Mvc.ControllerActionInvoker.InvokeActionMethod(ControllerContext controllerContext, ActionDescriptor actionDescriptor, IDictionary`2 parameters)
at System.Web.Mvc.Async.AsyncControllerActionInvoker.<BeginInvokeSynchronousActionMethod>b__39(IAsyncResult asyncResult, ActionInvocation innerInvokeState)
at System.Web.Mvc.Async.AsyncResultWrapper.WrappedAsyncResult`2.CallEndDelegate(IAsyncResult asyncResult)
at System.Web.Mvc.Async.AsyncResultWrapper.WrappedAsyncResultBase`1.End()
at System.Web.Mvc.Async.AsyncControllerActionInvoker.EndInvokeActionMethod(IAsyncResult asyncResult)
at System.Web.Mvc.Async.AsyncControllerActionInvoker.AsyncInvocationWithFilters.<InvokeActionMethodFilterAsynchronouslyRecursive>b__3d()
at System.Web.Mvc.Async.AsyncControllerActionInvoker.AsyncInvocationWithFilters.<>c__DisplayClass46.<InvokeActionMethodFilterAsynchronouslyRecursive>b__3f()

I literally found the answer two minutes after looking. But since I had a hard time Googling this answer I think it would be nice to place the answer here, instead of deleting the question.
I forgot to initialize the storage engine. I overlooked it because of the fluid syntax. The correct way to let NEventStore initialize the database is by including the InitializeStorageEngine method after you have selected the database type:
this.EventStore = Wireup.Init()
.LogToOutputWindow()
.UsingInMemoryPersistence()
.UsingSqlPersistence("DefaultConnection")
.WithDialect(new MsSqlDialect())
.InitializeStorageEngine() // The oh so important line!
.UsingJsonSerialization()
.LogToOutputWindow()
.Build();

Related

SqlPackage Object reference not set to an instance of an object

When I attempt to deploy DACPACs via SqlPackage.exe,
I encounter the error below :
An unexpected failure occurred: Object reference not set to an instance of an object..
Unhandled Exception: System.NullReferenceException: Object reference not set to an instance of an object.
at Microsoft.Data.Tools.Schema.Sql.SchemaModel.ReverseEngineerPopulators.Sql90TableBaseColumnPopulator`1.InsertElementIntoParent(SqlColumn element, TElement parent, ReverseEngineerOption option)
at Microsoft.Data.Tools.Schema.Sql.SchemaModel.ReverseEngineerPopulators.ChildModelElementPopulator`2.CreateChildElement(TParent parent, EventArgs e, ReverseEngineerOption option)
at Microsoft.Data.Tools.Schema.Sql.SchemaModel.ReverseEngineerPopulators.ChildModelElementPopulator`2.PopulateAllChildrenFromCache(IDictionary`2 cache, SqlReverseEngineerRequest request, OrdinalSqlDataReader reader, ReverseEngineerOption option)
at Microsoft.Data.Tools.Schema.Sql.SchemaModel.ReverseEngineerPopulators.TopLevelElementPopulator`1.Populate(SqlReverseEngineerRequest request, OrdinalSqlDataReader reader, ReverseEngineerOption option)
at Microsoft.Data.Tools.Schema.Sql.SchemaModel.SqlReverseEngineerImpl.ExecutePopulators(ReliableSqlConnection conn, IList`1 populators, Int32 totalPopulatorsCount, Int32 startIndex, Boolean progressAlreadyUpdated, ReverseEngineerOption option, SqlReverseEngineerRequest request)
at Microsoft.Data.Tools.Schema.Sql.SchemaModel.SqlReverseEngineerImpl.ExecutePopulatorsInPass(SqlReverseEngineerConnectionContext context, ReverseEngineerOption option, SqlReverseEngineerRequest request, Int32 totalCount, Tuple`2[] populatorsArray)
at Microsoft.Data.Tools.Schema.Sql.SchemaModel.SqlReverseEngineerImpl.PopulateBatch(SqlReverseEngineerConnectionContext context, SqlSchemaModel model, ReverseEngineerOption option, ErrorManager errorManager, SqlReverseEngineerRequest request, SqlImportScope importScope)
at Microsoft.Data.Tools.Schema.Sql.SchemaModel.SqlReverseEngineer.PopulateAll(SqlReverseEngineerConnectionContext context, ReverseEngineerOption option, ErrorManager errorManager, Boolean filterManagementScopedElements, SqlImportScope importScope, Boolean optimizeForQuery, ModelStorageType modelType)
at Microsoft.Data.Tools.Schema.Sql.Deployment.SqlDeploymentEndpointServer.ImportDatabase(SqlReverseEngineerConstructor constructor, DeploymentEngineContext context, ErrorManager errorManager)
at Microsoft.Data.Tools.Schema.Sql.Deployment.SqlDeploymentEndpointServer.OnLoad(ErrorManager errors, DeploymentEngineContext context)
at Microsoft.Data.Tools.Schema.Sql.Deployment.SqlDeployment.PrepareModels()
at Microsoft.Data.Tools.Schema.Sql.Deployment.SqlDeployment.InitializePlanGeneratator()
at Microsoft.SqlServer.Dac.DacServices.<>c__DisplayClass21.<CreateDeploymentArtifactGenerationOperation>b__1f(Object operation, CancellationToken token)
at Microsoft.SqlServer.Dac.Operation.Microsoft.SqlServer.Dac.IOperation.Run(OperationContext context)
at Microsoft.SqlServer.Dac.ReportMessageOperation.Microsoft.SqlServer.Dac.IOperation.Run(OperationContext context)
at Microsoft.SqlServer.Dac.OperationExtension.Execute(IOperation operation, DacLoggingContext loggingContext, CancellationToken cancellationToken)
at Microsoft.SqlServer.Dac.DacServices.GenerateDeployScript(DacPackage package, String targetDatabaseName, DacDeployOptions options, Nullable`1 cancellationToken)
at Microsoft.Data.Tools.Schema.CommandLineTool.DacServiceUtil.<>c__DisplayClasse.<DoDeployAction>b__4(DacServices service)
at Microsoft.Data.Tools.Schema.CommandLineTool.DacServiceUtil.ExecuteDeployOperation(String connectionString, String filePath, MessageWrapper messageWrapper, Boolean sourceIsPackage, Boolean targetIsPackage, Func`1 generateScriptFromPackage, Func`2 generateScriptFromDatabase)
at Microsoft.Data.Tools.Schema.CommandLineTool.DacServiceUtil.DoDeployAction(DeployArguments parsedArgs, Action`1 writeError, Action`2 writeMessage, Action`1 writeWarning)
at Microsoft.Data.Tools.Schema.CommandLineTool.Program.DoDeployActions(CommandLineArguments parsedArgs)
at Microsoft.Data.Tools.Schema.CommandLineTool.Program.Run(String[] args)
at Microsoft.Data.Tools.Schema.CommandLineTool.Program.Main(String[] args)
Below is the command I run:
SET vardeploy2=/Action:Script
set varBlockOnDriftParameter=/p:BlockWhenDriftDetected=False
"SSDTBinaries\SqlPackage.exe" %vardeploy2% %varBlockOnDriftParameter% /SourceFile:"dacpacs\DBName.dacpac" /Profile:"Profiles\%1.DBName.Publish.xml" >> Log.txt 2>>&1
I deploy to a SQL Server 2008 R2. The SqlPackage.exe version is 11.0.2820.0.
The issue is intermittent, which suggests it's not related to the DACPAC being deployed or the destination database's schema. My best guess is that something about the state of the database is causing the problem.
Still, I haven't been able to identify anything unusual at the time of the failures.
When recreating the issue locally, using schema locks results in a different error message.
Has anyone know of a solution?
Upgrade to a more resent SQL Server Data Tools.

EF code first migration error "Object has been disconnected or does not exist at the server"

I am using Entity Framework 6.1.1 on SQL Server 2008 and I have a long running code first migration (about 20 minutes). It gets to the end and then gives the following error.
System.Runtime.Remoting.RemotingException: Object '/f10901d8_94fe_4db4_bb9d_51cd19292b01/bq6vk4vkuz5tkri2x8nwhsln_106.rem' has been disconnected or does not exist at the server.
at System.Data.Entity.Migrations.Design.ToolingFacade.ToolLogger.Verbose(String sql)
at System.Data.Entity.Migrations.Infrastructure.MigratorLoggingDecorator.ExecuteSql(DbTransaction transaction, MigrationStatement migrationStatement, DbInterceptionContext interceptionContext)
at System.Data.Entity.Migrations.DbMigrator.ExecuteStatementsInternal(IEnumerable`1 migrationStatements, DbTransaction transaction, DbInterceptionContext interceptionContext)
at System.Data.Entity.Migrations.DbMigrator.ExecuteStatementsInternal(IEnumerable`1 migrationStatements, DbConnection connection)
at System.Data.Entity.Migrations.DbMigrator.<>c__DisplayClass30.<ExecuteStatements>b__2e()
at System.Data.Entity.SqlServer.DefaultSqlExecutionStrategy.<>c__DisplayClass1.<Execute>b__0()
at System.Data.Entity.SqlServer.DefaultSqlExecutionStrategy.Execute[TResult](Func`1 operation)
at System.Data.Entity.SqlServer.DefaultSqlExecutionStrategy.Execute(Action operation)
at System.Data.Entity.Migrations.DbMigrator.ExecuteStatements(IEnumerable`1 migrationStatements, DbTransaction existingTransaction)
at System.Data.Entity.Migrations.DbMigrator.ExecuteStatements(IEnumerable`1 migrationStatements)
at System.Data.Entity.Migrations.Infrastructure.MigratorBase.ExecuteStatements(IEnumerable`1 migrationStatements)
at System.Data.Entity.Migrations.DbMigrator.ExecuteOperations(String migrationId, XDocument targetModel, IEnumerable`1 operations, IEnumerable`1 systemOperations, Boolean downgrading, Boolean auto)
at System.Data.Entity.Migrations.DbMigrator.ApplyMigration(DbMigration migration, DbMigration lastMigration)
at System.Data.Entity.Migrations.Infrastructure.MigratorLoggingDecorator.ApplyMigration(DbMigration migration, DbMigration lastMigration)
at System.Data.Entity.Migrations.DbMigrator.Upgrade(IEnumerable`1 pendingMigrations, String targetMigrationId, String lastMigrationId)
at System.Data.Entity.Migrations.Infrastructure.MigratorLoggingDecorator.Upgrade(IEnumerable`1 pendingMigrations, String targetMigrationId, String lastMigrationId)
at System.Data.Entity.Migrations.DbMigrator.UpdateInternal(String targetMigration)
at System.Data.Entity.Migrations.DbMigrator.<>c__DisplayClassc.<Update>b__b()
at System.Data.Entity.Migrations.DbMigrator.EnsureDatabaseExists(Action mustSucceedToKeepDatabase)
at System.Data.Entity.Migrations.Infrastructure.MigratorBase.EnsureDatabaseExists(Action mustSucceedToKeepDatabase)
at System.Data.Entity.Migrations.DbMigrator.Update(String targetMigration)
at System.Data.Entity.Migrations.Infrastructure.MigratorBase.Update(String targetMigration)
at System.Data.Entity.Migrations.Design.ToolingFacade.UpdateRunner.Run()
at System.AppDomain.DoCallBack(CrossAppDomainDelegate callBackDelegate)
at System.AppDomain.DoCallBack(CrossAppDomainDelegate callBackDelegate)
at System.Data.Entity.Migrations.Design.ToolingFacade.Run(BaseRunner runner)
at System.Data.Entity.Migrations.Design.ToolingFacade.Update(String targetMigration, Boolean force)
at System.Data.Entity.Migrations.UpdateDatabaseCommand.<>c__DisplayClass2.<.ctor>b__0()
at System.Data.Entity.Migrations.MigrationsDomainCommand.Execute(Action command)
The point of the migration is to update a field in the database that stores the MIME type of some binary data. It loops through every row, reads the binary data, attempts to determine what kind of content it is, then writes the appropriate MIME type value into the that row.
The script below uses ADO.NET to generate a list of update statements to run. I use ADO.NET because I must use .NET's imaging libraries (System.Drawing.Imaging.ImageFormat) to determine the type of binary content in each row (it'll be a jpeg, png, or pdf).
public override void Up()
{
List<string> updateStatements = new List<string>();
using(SqlConnection conn = new SqlConnection(ConfigurationManager.AppSettings["ConnectionString"]))
{
SqlCommand cmd = new SqlCommand("SELECT Table1ID, Image FROM Table1"), conn);
conn.Open();
//read each record and update the content type value based on the type of data stored
using (SqlDataReader reader = cmd.ExecuteReader())
{
while (reader.Read())
{
long idValue = Convert.ToInt64(reader["Table1ID"]);
byte[] data = (byte[])reader["Image"];
string contentType = GetMimeType(data);
updateStatements.Add(string.Format("UPDATE Table1 SET Content_Type = {0} WHERE Table1ID = {1}", contentType, idValue));
}
}
}
foreach (string updateStatement in updateStatements)
Sql(updateStatement);
}
public string GetMimeType(byte[] document)
{
if (document != null && document.Length > 0)
{
ImageFormat format = null;
try
{
MemoryStream ms = new MemoryStream(document);
Image img = Image.FromStream(ms);
format = img.RawFormat;
}
catch (Exception)
{
/* PDF documents will throw exceptions since they aren't images but you can check if it's really a PDF
* by inspecting the first four bytes with will be 0x25 0x50 0x44 0x46 ("%PDF"). */
if (document[0] == 0x25 && document[1] == 0x50 && document[2] == 0x44 && document[3] == 0x46)
return PDF;
else
return NULL;
}
if (format.Equals(ImageFormat.Jpeg))
{
return JPG;
}
else if (format.Equals(System.Drawing.Imaging.ImageFormat.Png))
{
return PNG;
}
}
return NULL;
}
I've seen this five year old post and the articles that it links to do not seem to exist anymore. At least I can't find them.
Does anyone know what's going on here?
-- UPDATE --
This appears to have something to do with how long the migration takes to run. I created a migration that does absolutely nothing other than sleep for 22 minutes
public override void Up()
{
System.Threading.Thread.Sleep(1320000);
}
and I got the same error. So it appears to be a timeout thing. I'm not 100% what object on the server they are referring to and I can't find much on this issue as it relates to code first migrations.
I tried setting the CommandTimeout property in the migrations Configuration.cs file to 5000 but it didn't help. I also attempted to set the SQL Server's Remove query timeout setting to 0 to prevent any timeouts but it didn't help either.
Poached from [GitHub EntityFramework 6 Issue #96][https://github.com/aspnet/EntityFramework6/issues/96#issuecomment-289782427]
The issue is that the ToolLogger lease lifetime (base class
MigrationsLogger is a MarshalByRefObject) is at the default (5
minutes). The ToolingFacade creates the logger, which lives in the
main program's app domain. The migrations run in a different app
domain. If a migration takes longer than 5 minutes, the attempt to log
any further information results in this error. A solution would be to
increase the lease lifetime in the main program. So... in the main
program, prior to creating the ToolingFacade, set the lease lifetime
to a longer time period:
using System.Runtime.Remoting.Lifetime;
...
LifetimeServices.LeaseTime = TimeSpan.FromHours(1);
It's a known issue in Entity Framework 6 for scripts that take a long time to complete.
A workaround is to generate only SQL script via the Update-Database command and execute the generated SQL directly on the SQL Server. In order to generate only the SQL you have to use the -Script flag:
Update-Database -Script
This has been causing us headaches. The problem appears to be due to the design of the EF migration utility. The program creates a new AppDomain in which to run migrations. The logging for the new AppDomain is handled in the original AppDomain (which is why remoting gets involved). Apparently the logger gets GC'ed if an individual migration takes too much time. I've verified this by replacing all the logger calls with Console.WriteLine - which makes the problem go away. There may be a fix by altering the migrate.exe tool (but may possibly require altering EntityFramework assembly itself).
I had this problem because the connection string in my web.config was pointing to the wrong server name.
Actually, I had to change my c:\windows\system32\drivers\etc\host file to specify correct IP address for this DB host name.
Just make sure your DB server is accessible.

PostgreSQL + Npgsql connector + MVC and SimpleMembership Not working

I've test the db connection without Websecurity and it works. I've followed the tutorial from Brice Lambson http://brice-lambson.blogspot.com.es/2012/10/entity-framework-on-postgresql.html
But when I use
WebSecurity.InitializeDatabaseConnection("myContext",
"UserProfile", "UserId", "UserName", autoCreateTables: false);
I get this exception:
System.InvalidOperationException was caught
HResult=-2146233079
Message=No user table found that has the name "UserProfile".
Source=WebMatrix.WebData
StackTrace:
in WebMatrix.WebData.SimpleMembershipProvider.ValidateUserTable()
in WebMatrix.WebData.WebSecurity.InitializeMembershipProvider(SimpleMembershipProvider simpleMembership, DatabaseConnectionInfo connect, String userTableName, String userIdColumn, String userNameColumn, Boolean createTables)
in WebMatrix.WebData.WebSecurity.InitializeProviders(DatabaseConnectionInfo connect, String userTableName, String userIdColumn, String userNameColumn, Boolean autoCreateTables)
in WebMatrix.WebData.WebSecurity.InitializeDatabaseConnection(String connectionStringName, String userTableName, String userIdColumn, String userNameColumn, Boolean autoCreateTables)
in Glink.Filters.InitializeSimpleMembershipAttribute.SimpleMembershipInitializer..ctor() en c:\Users\...\InitializeSimpleMembershipAttribute.cs:line 46
InnerException: Npgsql.NpgsqlException
HResult=-2147467259
Message=ERROR: 42601: Syntax error near «[»
Source=Npgsql
ErrorCode=-2147467259
BaseMessage=Syntax error near «[»
Code=42601
Detail=""
ErrorSql=SELECT [UserId] FROM [UserProfile] WHERE (UPPER([UserName]) = ((E'Z')))
File=src\backend\parser\scan.l
Hint=""
Line=1002
Position=8
Routine=scanner_yyerror
Severity=ERROR
Where=""
StackTrace:
in Npgsql.NpgsqlState.<ProcessBackendResponses_Ver_3>d__a.MoveNext()
in Npgsql.ForwardsOnlyDataReader.GetNextResponseObject()
in Npgsql.ForwardsOnlyDataReader.GetNextRowDescription()
in Npgsql.ForwardsOnlyDataReader.NextResult()
in Npgsql.ForwardsOnlyDataReader..ctor(IEnumerable`1 dataEnumeration, CommandBehavior behavior, NpgsqlCommand command, NotificationThreadBlock threadBlock, Boolean synchOnReadError)
in Npgsql.NpgsqlCommand.GetReader(CommandBehavior cb)
in Npgsql.NpgsqlCommand.ExecuteScalar()
in WebMatrix.Data.Database.QueryValue(String commandText, Object[] args)
in WebMatrix.WebData.DatabaseWrapper.QueryValue(String commandText, Object[] parameters)
in WebMatrix.WebData.SimpleMembershipProvider.GetUserId(IDatabase db, String userTableName, String userNameColumn, String userIdColumn, String userName)
in WebMatrix.WebData.SimpleMembershipProvider.ValidateUserTable()
InnerException:
I guess that NpgSql could not be prepared to work with SimpleMerbership, but I'd like to know if any of you had tried this.
Thank you!!
You should try Daniel Nauck's AspSQLProvider: http://dev.nauck-it.de/projects/show/aspsqlprovider
It is a PostgreSQL implementation of the ASP.NET 2.0+ Membership, Role, Profile and Session-State Store Provider.
I hope it helps.
I'd hint you to try changing "autoCreateTables: false" to "autoCreateTables: true".
Doesn't work with postgres because it injects brackets ([ ... ]) into throughout the embedded SQL:
https://github.com/aspnetwebstack/aspnetwebstack/blob/master/src/WebMatrix.WebData/SimpleMembershipProvider.cs

Using CodeFirst.DontDropDbJustCreateTablesIfModelChanged causes attachment issues to the ObjectStateManager in EF 4.3

[EDIT]: The application works fine in my local but won't run in AppHarbor. At the initial load of my site, I'd get this error mentioned in another question, if I reload the page then I'd get the error mentioned below. As mentioned by appharbor's Admin, they are working on the problem with new relic and ninject. But I'm not quite sure if my 2nd error is still related with appharbor's issue with new relic. Does Devtalk.EF.CodeFirst.DontDropDbJustCreateTablesIfModelChanged work properly with EF 4.3? Do I just wait on their update?
[InvalidOperationException: The object cannot be detached because it is not attached to the ObjectStateManager.]
at System.Data.Objects.ObjectContext.Detach(Object entity, EntitySet expectedEntitySet)
at System.Data.Objects.ObjectContext.Detach(Object entity)
at Devtalk.EF.CodeFirst.DontDropDbJustCreateTablesIfModelChanged`1.SaveModelHashToDatabase(T context, String modelHash, ObjectContext objectContext)
at Devtalk.EF.CodeFirst.DontDropDbJustCreateTablesIfModelChanged`1.InitializeDatabase(T context)
at System.Data.Entity.Database.<>c__DisplayClass2`1.<SetInitializerInternal>b__0(DbContext c)
at System.Data.Entity.Internal.InternalContext.<>c__DisplayClass8.<PerformDatabaseInitialization>b__6()
at System.Data.Entity.Internal.InternalContext.PerformInitializationAction(Action action)
at System.Data.Entity.Internal.InternalContext.PerformDatabaseInitialization()
at System.Data.Entity.Internal.LazyInternalContext.<InitializeDatabase>b__4(InternalContext c)
at System.Data.Entity.Internal.RetryAction`1.PerformAction(TInput input)
at System.Data.Entity.Internal.LazyInternalContext.InitializeDatabaseAction(Action`1 action)
at System.Data.Entity.Internal.LazyInternalContext.InitializeDatabase()
at System.Data.Entity.Internal.InternalContext.Initialize()
at System.Data.Entity.Internal.InternalContext.GetEntitySetAndBaseTypeForType(Type entityType)
at System.Data.Entity.Internal.Linq.InternalSet`1.Initialize()
at System.Data.Entity.Internal.Linq.InternalSet`1.get_InternalContext()
at System.Data.Entity.Infrastructure.DbQuery`1.System.Linq.IQueryable.get_Provider()
at System.Linq.Queryable.Where[TSource](IQueryable`1 source, Expression`1 predicate)
at Core.Repository`2.Find(Expression`1 predicate) in d:\temp\2otuf0q2.xtn\input\Domain\Core\Repository.cs:line 52
at Data.RegistrantRepository.GetAllRegistrant() in d:\temp\2otuf0q2.xtn\input\Data\Data\RegistrantRepository.cs:line 20
at IPOD.Controllers.HomeController.Index() in d:\temp\2otuf0q2.xtn\input\IPOD\Controllers\HomeController.cs:line 28
at lambda_method(Closure , ControllerBase , Object[] )
at System.Web.Mvc.ActionMethodDispatcher.Execute(ControllerBase controller, Object[] parameters)
at System.Web.Mvc.ReflectedActionDescriptor.Execute(ControllerContext controllerContext, IDictionary`2 parameters)
at System.Web.Mvc.ControllerActionInvoker.InvokeActionMethod(ControllerContext controllerContext, ActionDescriptor actionDescriptor, IDictionary`2 parameters)
at System.Web.Mvc.ControllerActionInvoker.<>c__DisplayClass15.<InvokeActionMethodWithFilters>b__12()
at System.Web.Mvc.ControllerActionInvoker.InvokeActionMethodFilter(IActionFilter filter, ActionExecutingContext preContext, Func`1 continuation)
at System.Web.Mvc.ControllerActionInvoker.<>c__DisplayClass15.<>c__DisplayClass17.<InvokeActionMethodWithFilters>b__14()
at System.Web.Mvc.ControllerActionInvoker.InvokeActionMethodWithFilters(ControllerContext controllerContext, IList`1 filters, ActionDescriptor actionDescriptor, IDictionary`2 parameters)
at System.Web.Mvc.ControllerActionInvoker.InvokeAction(ControllerContext controllerContext, String actionName)
at System.Web.Mvc.Controller.ExecuteCore()
at System.Web.Mvc.ControllerBase.Execute(RequestContext requestContext)
at System.Web.Mvc.ControllerBase.System.Web.Mvc.IController.Execute(RequestContext requestContext)
at System.Web.Mvc.MvcHandler.<>c__DisplayClass6.<>c__DisplayClassb.<BeginProcessRequest>b__5()
at System.Web.Mvc.Async.AsyncResultWrapper.<>c__DisplayClass1.<MakeVoidDelegate>b__0()
at System.Web.Mvc.Async.AsyncResultWrapper.<>c__DisplayClass8`1.<BeginSynchronous>b__7(IAsyncResult _)
at System.Web.Mvc.Async.AsyncResultWrapper.WrappedAsyncResult`1.End()
at System.Web.Mvc.Async.AsyncResultWrapper.End[TResult](IAsyncResult asyncResult, Object tag)
at System.Web.Mvc.Async.AsyncResultWrapper.End(IAsyncResult asyncResult, Object tag)
at System.Web.Mvc.MvcHandler.<>c__DisplayClasse.<EndProcessRequest>b__d()
at System.Web.Mvc.SecurityUtil.<GetCallInAppTrustThunk>b__0(Action f)
at System.Web.Mvc.SecurityUtil.ProcessInApplicationTrust(Action action)
at System.Web.Mvc.MvcHandler.EndProcessRequest(IAsyncResult asyncResult)
at System.Web.Mvc.MvcHandler.System.Web.IHttpAsyncHandler.EndProcessRequest(IAsyncResult result)
at System.Web.HttpApplication.CallHandlerExecutionStep.System.Web.HttpApplication.IExecutionStep.Execute()
at System.Web.HttpApplication.ExecuteStep(IExecutionStep step, Boolean& completedSynchronously)
For me it looks like the initializer is trying to update the EdmMetadata table - at least this is what I infere from:
Devtalk.EF.CodeFirst.DontDropDbJustCreateTablesIfModelChanged`1.SaveModelHashToDatabase(T context, String modelHash, ObjectContext objectContext)
In EF 4.3 the EdmMeatadata table will not be created (it will be used though if you have one in your database and model did not change - i.e. when you upgrade from 4.1/4.2 to 4.3+ - for more details see: http://blog.oneunicorn.com/2012/01/13/ef-4-3-beta-1-what-happened-to-that-edmmetadata-table/)
In 4.3 world you want to use migrations if your model changes and you need to update the database but don't want to actually delete and recreate it. Take a look at this walkthorugh: http://blogs.msdn.com/b/adonet/archive/2012/02/09/ef-4-3-code-based-migrations-walkthrough.aspx

EF 5 Beta 1 Code First - Sequence contains more than one element

I am attempting to upgrade my solution from the June 2011 CTP of EF Code First to EF 5 Beta.
I now have the following problem:
After creating an instance of the context, I get the exception listed below when I try and query the context.
It seems as if between the two versions of EF, something has changed whereby it is now having a problem with dealing with the configuration but I am at a loss in terms of where to start looking.
Many thanks in advance for any help.
Paul.
System.InvalidOperationException was unhandled by user code
HResult=-2146233079 Message=Sequence contains more than one element
Source=System.Core StackTrace:
at System.Linq.Enumerable.SingleOrDefault[TSource](IEnumerable1 source)
at System.Data.Entity.ModelConfiguration.Configuration.Properties.Navigation.NavigationPropertyConfiguration.Configure(DbDatabaseMapping
databaseMapping)
at System.Data.Entity.ModelConfiguration.Configuration.Types.EntityTypeConfiguration.<>c__DisplayClass36.<ConfigureAssociationMappings>b__35(NavigationPropertyConfiguration c)
at System.Data.Entity.ModelConfiguration.Utilities.IEnumerableExtensions.Each[T](IEnumerable1
ts, Action1 action)
at System.Data.Entity.ModelConfiguration.Configuration.Types.EntityTypeConfiguration.ConfigureAssociationMappings(DbDatabaseMapping
databaseMapping)
at System.Data.Entity.ModelConfiguration.Configuration.Types.EntityTypeConfiguration.Configure(EdmEntityType
entityType, DbDatabaseMapping databaseMapping, DbProviderManifest
providerManifest)
at System.Data.Entity.ModelConfiguration.Configuration.ModelConfiguration.ConfigureEntityTypes(DbDatabaseMapping
databaseMapping, DbProviderManifest providerManifest)
at System.Data.Entity.ModelConfiguration.Configuration.ModelConfiguration.Configure(DbDatabaseMapping
databaseMapping, DbProviderManifest providerManifest)
at System.Data.Entity.DbModelBuilder.Build(DbProviderManifest providerManifest, DbProviderInfo providerInfo)
at System.Data.Entity.DbModelBuilder.Build(DbConnection providerConnection)
at System.Data.Entity.Internal.LazyInternalContext.CreateModel(LazyInternalContext
internalContext)
at System.Data.Entity.Internal.RetryLazy2.GetValue(TInput input)
at System.Data.Entity.Internal.LazyInternalContext.InitializeContext()
at System.Data.Entity.Internal.InternalContext.Initialize()
at System.Data.Entity.Internal.InternalContext.ForceOSpaceLoadingForKnownEntityTypes()
at System.Data.Entity.DbContext.System.Data.Entity.Infrastructure.IObjectContextAdapter.get_ObjectContext()
at AccessAccounts.Accounts.DataAccess.Context.AccountsContext..ctor(String
connectionString) in c:\Source\EnterpriseVS11\Enterprise\Data Access
EF\Context\AccountsContext.cs:line 77
at AccessAccounts.BusinessService.Logon.LogonService.CheckDatabaseCompatibility()
in c:\Source\EnterpriseVS11\Enterprise\Business
Service\src\AccessAccounts\BusinessService\Logon\LogonService.cs:line
119
at AccessAccounts.BusinessService.Logon.LogonService.Logon(ApplicationTypes
applicationType, String databaseName, String userName, String
password, AuthenticationType authenticationMode) in
c:\Source\EnterpriseVS11\Enterprise\Business
Service\src\AccessAccounts\BusinessService\Logon\LogonService.cs:line
255
at SyncInvokeLogon(Object , Object[] , Object[] )
at System.ServiceModel.Dispatcher.SyncMethodInvoker.Invoke(Object
instance, Object[] inputs, Object[]& outputs)
at System.ServiceModel.Dispatcher.DispatchOperationRuntime.InvokeBegin(MessageRpc&
rpc) InnerException:
This is a known bug in EF5 Beta 1. We are going to fix this in Beta 2, which will be dropping within the next couple of weeks.
The bug only affects Independent Association (associations where the FK does not exist in your CLR classes) so you can workaround by switching to FK associations.