Data Entities Add Range quit working - entity-framework

Like the title suggests I have a small program that has been running in production for the last 3 months. Last week it started to error out on an AddRange line with this error message:
"Message=Keyword not supported: 'file'."
And nothing in the inner exception. Here is the offending function where I can no longer get to the SaveChanges() line.
private static void SaveToDB(List<MarketNew> inMarketNews)
{
proxy.MarketNews.AddRange(inMarketNews);
proxy.SaveChanges();
}
cheers
bob
edit-
If I try to manually add them one at a time I still receive the following exception.
System.ArgumentException was caught
HResult=-2147024809
Message=Keyword not supported: 'file'.
Source=System.Data
StackTrace:
at System.Data.Common.DbConnectionOptions.ParseInternal(Hashtable parsetable, String connectionString, Boolean buildChain, Hashtable synonyms, Boolean firstKey)
at System.Data.Common.DbConnectionOptions..ctor(String connectionString, Hashtable synonyms, Boolean useOdbcRules)
at System.Data.SqlClient.SqlConnectionString..ctor(String connectionString)
at System.Data.SqlClient.SqlConnectionFactory.CreateConnectionOptions(String connectionString, DbConnectionOptions previous)
at System.Data.ProviderBase.DbConnectionFactory.GetConnectionPoolGroup(DbConnectionPoolKey key, DbConnectionPoolGroupOptions poolOptions, DbConnectionOptions& userConnectionOptions)
at System.Data.SqlClient.SqlConnection.ConnectionString_Set(DbConnectionPoolKey key)
at System.Data.SqlClient.SqlConnection.set_ConnectionString(String value)
at System.Data.Entity.Infrastructure.Interception.DbConnectionDispatcher.<SetConnectionString>b__18(DbConnection t, DbConnectionPropertyInterceptionContext`1 c)
at System.Data.Entity.Infrastructure.Interception.InternalDispatcher`1.Dispatch[TTarget,TInterceptionContext](TTarget target, Action`2 operation, TInterceptionContext interceptionContext, Action`3 executing, Action`3 executed)
at System.Data.Entity.Infrastructure.Interception.DbConnectionDispatcher.SetConnectionString(DbConnection connection, DbConnectionPropertyInterceptionContext`1 interceptionContext)
at System.Data.Entity.Infrastructure.SqlConnectionFactory.CreateConnection(String nameOrConnectionString)
at System.Data.Entity.Internal.LazyInternalConnection.Initialize()
at System.Data.Entity.Internal.LazyInternalConnection.get_ProviderName()
at System.Data.Entity.Internal.LazyInternalContext.get_ProviderName()
at System.Data.Entity.Internal.DefaultModelCacheKeyFactory.Create(DbContext context)
at System.Data.Entity.Internal.LazyInternalContext.InitializeContext()
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.Internal.Linq.InternalSet`1.AddRange(IEnumerable entities)
at System.Data.Entity.DbSet`1.AddRange(IEnumerable`1 entities)
at GetMarketNews.Program.SaveToDB(List`1 inMarketNews) in e:\Tableau\Custom Utilities\MarketNews\GetMarketNews\GetMarketNews\Program.cs:line 195
InnerException:

The exception indicates that there is a problem with your connection string. While the program itself may not have been changed in months, can you confirm that the config file (or however you set your connection string) has not been changed?
If you still can't find it from this, I would suggest you check out the value of the connection string at runtime (e.g. put a breakpoint on the AddRange line, and look at proxy.Database.ConnectionString). I suspect you'll find the "file" keyword in the connection string.

Related

After update to .NET 7, I get an error : System.ArgumentException: An item with the same key has already been added

I created a project with ASP.NET Core 6 and developed it over time.
Now I updated this project to .NET 7.
So far there have been no problems. I had no errors at runtime. The program works correctly.
After the update, when I run the add--migration command, I encounter an error whose origin is unknown.
I updated all nuget packages of the program.
Add-Migration -name test2 Build started... Build succeeded.
at System.Collections.Generic.Dictionary`2.TryInsert(TKey key, TValue value, InsertionBehavior behavior)
at System.Collections.Generic.Dictionary`2.Add(TKey key, TValue value)
at System.Linq.Enumerable.ToDictionary[TSource,TKey](IEnumerable`1 source, Func`2 keySelector, IEqualityComparer`1 comparer)
at Microsoft.EntityFrameworkCore.Migrations.Internal.MigrationsModelDiffer.AddSeedData(IEntityType entityType, Dictionary`2 identityMaps, EntityState initialState)
at Microsoft.EntityFrameworkCore.Migrations.Internal.MigrationsModelDiffer.TrackData(IRelationalModel source, IRelationalModel target, DiffContext diffContext)
at Microsoft.EntityFrameworkCore.Migrations.Internal.MigrationsModelDiffer.GetDataOperations(IRelationalModel source, IRelationalModel target, DiffContext diffContext)+MoveNext()
at System.Linq.Enumerable.ConcatIterator`1.MoveNext()
at Microsoft.EntityFrameworkCore.Migrations.Internal.MigrationsModelDiffer.Sort(IEnumerable`1 operations, DiffContext diffContext)
at Microsoft.EntityFrameworkCore.Migrations.Internal.MigrationsModelDiffer.GetDifferences(IRelationalModel source, IRelationalModel target)
at Microsoft.EntityFrameworkCore.Migrations.Design.MigrationsScaffolder.ScaffoldMigration(String migrationName, String rootNamespace, String subNamespace, String language)
at Microsoft.EntityFrameworkCore.Design.Internal.MigrationsOperations.AddMigration(String name, String outputDir, String contextType, String namespace)
at Microsoft.EntityFrameworkCore.Design.OperationExecutor.AddMigrationImpl(String name, String outputDir, String contextType, String namespace)
at Microsoft.EntityFrameworkCore.Design.OperationExecutor.AddMigration.<>c__DisplayClass0_0.<.ctor>b__0()
at Microsoft.EntityFrameworkCore.Design.OperationExecutor.OperationBase.<>c__DisplayClass3_0`1.<Execute>b__0()
at Microsoft.EntityFrameworkCore.Design.OperationExecutor.OperationBase.Execute(Action action)
An item with the same key has already been added. Key: Description
I used nlog to debug and I got this error.
Microsoft.Extensions.Hosting.HostAbortedException: The host was aborted. at Microsoft.Extensions.Hosting.HostFactoryResolver.HostingListener.ThrowHostAborted() at Microsoft.Extensions.Hosting.HostFactoryResolver.HostingListener.OnNext(KeyValuePair`2 value) at System.Diagnostics.DiagnosticListener.Write(String name, Object value) at Microsoft.Extensions.Hosting.HostBuilder.ResolveHost(IServiceProvider serviceProvider, DiagnosticListener diagnosticListener) at Microsoft.Extensions.Hosting.HostApplicationBuilder.Build() at Microsoft.AspNetCore.Builder.WebApplicationBuilder.Build() at Program.<Main>$(String[] args) in H:\Project\Rafa\erp\WebUI\Program.cs:line 61
I changed nullable values with ?
And I also put nullables context in the disable mode in the build propetries
I also used Debugger.Launch, but i got an error on
var app = builder.Build();
I encountered an exception
Microsoft.Extensions.Hosting.HostAbortedException
HResult=0x80131500
Message=The host was aborted.
Source=Microsoft.EntityFrameworkCore.Design
StackTrace:
at Microsoft.Extensions.Hosting.HostFactoryResolver.HostingListener.ThrowHostAborted()
at Microsoft.Extensions.Hosting.HostFactoryResolver.HostingListener.OnNext(KeyValuePair`2 value)
at System.Diagnostics.DiagnosticListener.Write(String name, Object value)
at Microsoft.Extensions.Hosting.HostBuilder.ResolveHost(IServiceProvider serviceProvider, DiagnosticListener diagnosticListener)
at Microsoft.Extensions.Hosting.HostApplicationBuilder.Build()
at Microsoft.AspNetCore.Builder.WebApplicationBuilder.Build()
at Program.<Main>$(String[] args) in H:\Project\Rafa\erp\WebUI\Program.cs:line 61
This exception was originally thrown at this call stack:
[External Code]
Program.<Main>$(string[]) in Program.cs

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.

find out the exact entity causing an exception in entity framework

The entity framework gives me generic messages in the exception without telling me the exact entity and the attribute which caused the error. How do I get more information about the error?
This happens in many cases such as
The operation failed: The relationship could not be changed because one or more of the foreign-key properties is non-nullable. When a change is made to a relationship, the related foreign-key property is set to a null value. If the foreign-key does not support null values, a new relationship must be defined, the foreign-key property must be assigned another non-null value, or the unrelated object must be deleted.
and
The conversion of a datetime2 data type to a datetime data type resulted in an out-of-range value. The statement has been terminated.
Exception details:
[SqlException (0x80131904): The conversion of a datetime2 data type to a datetime data type resulted in an out-of-range value.
The statement has been terminated.]
System.Data.SqlClient.SqlConnection.OnError(SqlException exception, Boolean breakConnection) +404
System.Data.SqlClient.TdsParser.ThrowExceptionAndWarning() +412
System.Data.SqlClient.TdsParser.Run(RunBehavior runBehavior, SqlCommand cmdHandler, SqlDataReader dataStream, BulkCopySimpleResultSet bulkCopyHandler, TdsParserStateObject stateObj) +2660
System.Data.SqlClient.SqlDataReader.ConsumeMetaData() +59
System.Data.SqlClient.SqlDataReader.get_MetaData() +118
System.Data.SqlClient.SqlCommand.FinishExecuteReader(SqlDataReader ds, RunBehavior runBehavior, String resetOptionsString) +6431425
System.Data.SqlClient.SqlCommand.RunExecuteReaderTds(CommandBehavior cmdBehavior, RunBehavior runBehavior, Boolean returnStream, Boolean async) +6432994
System.Data.SqlClient.SqlCommand.RunExecuteReader(CommandBehavior cmdBehavior, RunBehavior runBehavior, Boolean returnStream, String method, DbAsyncResult result) +538
System.Data.SqlClient.SqlCommand.RunExecuteReader(CommandBehavior cmdBehavior, RunBehavior runBehavior, Boolean returnStream, String method) +28
System.Data.SqlClient.SqlCommand.ExecuteReader(CommandBehavior behavior, String method) +256
System.Data.SqlClient.SqlCommand.ExecuteDbDataReader(CommandBehavior behavior) +19
System.Data.Mapping.Update.Internal.DynamicUpdateCommand.Execute(UpdateTranslator translator, EntityConnection connection, Dictionary2 identifierValues, List1 generatedValues) +270
System.Data.Mapping.Update.Internal.UpdateTranslator.Update(IEntityStateManager stateManager, IEntityAdapter adapter) +391
[UpdateException: An error occurred while updating the entries. See the inner exception for details.]
System.Data.Mapping.Update.Internal.UpdateTranslator.Update(IEntityStateManager stateManager, IEntityAdapter adapter) +11223976
System.Data.Objects.ObjectContext.SaveChanges(SaveOptions options) +833
System.Data.Entity.Internal.InternalContext.SaveChanges() +218
[DbUpdateException: An error occurred while updating the entries. See the inner exception for details.]
System.Data.Entity.Internal.InternalContext.SaveChanges() +291
Here's the code I have in my solution:
try
{
_context.SaveChanges();
}
catch (System.Data.Entity.Validation.DbEntityValidationException dbEx)
{
Exception raise = dbEx;
foreach (var validationErrors in dbEx.EntityValidationErrors)
{
foreach (var validationError in validationErrors.ValidationErrors)
{
string message = string.Format("{0}:{1}", validationErrors.Entry.Entity.ToString(), validationError.ErrorMessage);
//raise a new exception inserting the current one as the InnerException
raise = new InvalidOperationException(message , raise);
}
}
throw raise;
}
You can use it as a basis to add into your solution ... it builds a nested set of exceptions with all the details from Entity Framework.
You need to write tests for repositories and in the base class for your tests:
try
{
DbContext.SaveChanges();
}
catch (DbEntityValidationException e)
{
e.EntityValidationErrors.SelectMany(error => error.ValidationErrors).ToList().ForEach(
item => Console.WriteLine("{0} - {1}", item.PropertyName, item.ErrorMessage));
throw;
}

Entity Framework Migrations - support for dynamic connection string

I can't make the migrations work for a specific scenario.
Our application uses two different models. The first is for the main database and there, the migration is working fine. The second model is for our customers databases which are specific for each customer (of course...) but all share the same model.
So, in the application (ASP.Net MVC 3), we identify the customer using the route and all customers are hosted in the same application. So, for each request we pass a key to our customer model dbContext constructor and with that key we recover the connection string through a simple helper method.
The application is working fine but not the migrations since I found no way to pass the key in the Package Manager Console.
I tried to create my own IDbConnectionFactory but it is not taken into account.
If I try an update-database command with the connection factory I get the following error which is normal since no key is passed but I can see that my connection factory is kicking in (EFCustomerModel.EFConnectionFactory):
PM> update-database -verbose
Using NuGet project 'EFCustomerModel'.
Using StartUp project 'PMEL.DatabaseSetup'.
System.ArgumentException: Format of the initialization string does not conform to specification starting at index 0.
at System.Data.Common.DbConnectionOptions.GetKeyValuePair(String connectionString, Int32 currentPosition, StringBuilder buffer, Boolean useOdbcRules, String& keyname, String& keyvalue)
at System.Data.Common.DbConnectionOptions.ParseInternal(Hashtable parsetable, String connectionString, Boolean buildChain, Hashtable synonyms, Boolean firstKey)
at System.Data.Common.DbConnectionOptions..ctor(String connectionString, Hashtable synonyms, Boolean useOdbcRules)
at System.Data.SqlClient.SqlConnectionString..ctor(String connectionString)
at System.Data.SqlClient.SqlConnectionFactory.CreateConnectionOptions(String connectionString, DbConnectionOptions previous)
at System.Data.ProviderBase.DbConnectionFactory.GetConnectionPoolGroup(String connectionString, DbConnectionPoolGroupOptions poolOptions, DbConnectionOptions& userConnectionOptions)
at System.Data.SqlClient.SqlConnection.ConnectionString_Set(String value)
at System.Data.SqlClient.SqlConnection.set_ConnectionString(String value)
at System.Data.SqlClient.SqlConnection..ctor(String connectionString)
**at EFCustomerModel.EFConnectionFactory.CreateConnection(String nameOrConnectionString) in C:\...\EFCustomerModel\EFConnectionFactory.vb:line 18**
at System.Data.Entity.Internal.LazyInternalConnection.Initialize()
at System.Data.Entity.Internal.LazyInternalConnection.get_Connection()
at System.Data.Entity.Internal.LazyInternalContext.get_Connection()
at System.Data.Entity.Infrastructure.DbContextInfo..ctor(Type contextType, DbProviderInfo modelProviderInfo, AppConfig config, DbConnectionInfo connectionInfo)
at System.Data.Entity.Infrastructure.DbContextInfo..ctor(Type contextType)
at System.Data.Entity.Migrations.DbMigrator..ctor(DbMigrationsConfiguration configuration, DbContext usersContext)
at System.Data.Entity.Migrations.DbMigrator..ctor(DbMigrationsConfiguration configuration)
at System.Data.Entity.Migrations.Design.ToolingFacade.BaseRunner.GetMigrator()
at System.Data.Entity.Migrations.Design.ToolingFacade.UpdateRunner.RunCore()
at System.Data.Entity.Migrations.Design.ToolingFacade.BaseRunner.Run()
Format of the initialization string does not conform to specification starting at index 0.
But when I try to pass in my key using the -ConnectionString parameter, then my connection factory is ignored and I get the same error:
PM> update-database -verbose -ConnectionString:CC99999 -ConnectionProviderName:System.Data.SqlClient
Using NuGet project 'EFCustomerModel'.
Using StartUp project 'PMEL.DatabaseSetup'.
System.ArgumentException: Format of the initialization string does not conform to specification starting at index 0.
at System.Data.Common.DbConnectionOptions.GetKeyValuePair(String connectionString, Int32 currentPosition, StringBuilder buffer, Boolean useOdbcRules, String& keyname, String& keyvalue)
at System.Data.Common.DbConnectionOptions.ParseInternal(Hashtable parsetable, String connectionString, Boolean buildChain, Hashtable synonyms, Boolean firstKey)
at System.Data.Common.DbConnectionOptions..ctor(String connectionString, Hashtable synonyms, Boolean useOdbcRules)
at System.Data.SqlClient.SqlConnectionString..ctor(String connectionString)
at System.Data.SqlClient.SqlConnectionFactory.CreateConnectionOptions(String connectionString, DbConnectionOptions previous)
at System.Data.ProviderBase.DbConnectionFactory.GetConnectionPoolGroup(String connectionString, DbConnectionPoolGroupOptions poolOptions, DbConnectionOptions& userConnectionOptions)
at System.Data.SqlClient.SqlConnection.ConnectionString_Set(String value)
at System.Data.SqlClient.SqlConnection.set_ConnectionString(String value)
at System.Data.Entity.Internal.LazyInternalConnection.InitializeFromConnectionStringSetting(ConnectionStringSettings appConfigConnection)
at System.Data.Entity.Internal.LazyInternalConnection.Initialize()
at System.Data.Entity.Internal.LazyInternalConnection.get_Connection()
at System.Data.Entity.Internal.LazyInternalContext.get_Connection()
at System.Data.Entity.Infrastructure.DbContextInfo..ctor(Type contextType, DbProviderInfo modelProviderInfo, AppConfig config, DbConnectionInfo connectionInfo)
at System.Data.Entity.Infrastructure.DbContextInfo..ctor(Type contextType, DbConnectionInfo connectionInfo)
at System.Data.Entity.Migrations.DbMigrator..ctor(DbMigrationsConfiguration configuration, DbContext usersContext)
at System.Data.Entity.Migrations.DbMigrator..ctor(DbMigrationsConfiguration configuration)
at System.Data.Entity.Migrations.Design.ToolingFacade.BaseRunner.GetMigrator()
at System.Data.Entity.Migrations.Design.ToolingFacade.UpdateRunner.RunCore()
at System.Data.Entity.Migrations.Design.ToolingFacade.BaseRunner.Run()
Format of the initialization string does not conform to specification starting at index 0.
So, is this an unsupported scenario in the migrations or there is another way to pass in my key or maybe there is another way to generate my connection strings?
You should be able to pass a key to your custom connection factory with the -ConnectionStringName parameter. This parameter would be passed to the CreateConnection method.
Another possible solution would be to call DB migration from your code:
var configuration = new Configuration();
configuration.TargetDatabase = new DbConnectionInfo(
"Server=MyServer;Database=MyDatabase;Trusted_Connection=True;",
"System.Data.SqlClient");
var migrator = new DbMigrator(configuration);
migrator.Update();

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.