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.
This commit is contained in:
rowanmiller 2014-03-31 10:45:41 -07:00
parent 351964878f
commit dabb68cc6d
1 changed files with 7 additions and 1 deletions

View File

@ -36,9 +36,15 @@ namespace MusicStore.Web.Models
private static void AddOrUpdate<TEntity>(Func<TEntity, object> propertyToMatch, IEnumerable<TEntity> entities)
where TEntity : class
{
// Query in a separate context so that we can attach existing entities as modified
List<TEntity> existingData;
using (var db = new MusicStoreContext())
{
existingData = db.Set<TEntity>().ToList();
}
using (var db = new MusicStoreContext())
{
var existingData = db.Set<TEntity>().ToList();
foreach (var item in entities)
{
db.ChangeTracker.Entry(item).State = existingData.Any(g => propertyToMatch(g).Equals(propertyToMatch(item)))