From dabb68cc6d1987f899cdcab5a7903698b3b42e23 Mon Sep 17 00:00:00 2001 From: rowanmiller Date: Mon, 31 Mar 2014 10:45:41 -0700 Subject: [PATCH] Fix EF InvalidOperationException on Startup The code that does an 'UPSERT' of seed data on app start was querying existing instances and attaching as modified of seed instances on the same context. Now that we track query results this will throw because the context has two instances of the same entity (same key value). Swapping to use a temporary context to query existing data. --- src/MusicStore/Models/SampleData.cs | 8 +++++++- 1 file changed, 7 insertions(+), 1 deletion(-) diff --git a/src/MusicStore/Models/SampleData.cs b/src/MusicStore/Models/SampleData.cs index 14bb4f0414..f432297346 100644 --- a/src/MusicStore/Models/SampleData.cs +++ b/src/MusicStore/Models/SampleData.cs @@ -36,9 +36,15 @@ namespace MusicStore.Web.Models private static void AddOrUpdate(Func propertyToMatch, IEnumerable entities) where TEntity : class { + // Query in a separate context so that we can attach existing entities as modified + List existingData; + using (var db = new MusicStoreContext()) + { + existingData = db.Set().ToList(); + } + using (var db = new MusicStoreContext()) { - var existingData = db.Set().ToList(); foreach (var item in entities) { db.ChangeTracker.Entry(item).State = existingData.Any(g => propertyToMatch(g).Equals(propertyToMatch(item)))