Duplicate Records from Migration Seed

I am writing a contact management application as a vehicle for my ASP.NET MVC learning using Entity Framework 6. To pre-load some test data I utilize the Seed method found in Migrations\Configuration.cs which gets added when migrations are enabled for a project.

When testing the contact creation process I noticed that I forgot to add a property for contact’s state. Easy enough to fix. I opened up the Contact class, added the missing state property and updated all the related views. Then I ran the app to test my change and was greeted with this error:ContextChanged

Of course the model backing my DbContext has changed since the database was created, I just added a new property to the model. Being new to entity framework workflow I often see this error when I forget to update the database before running the app to try out a change. It is easy to fix by using the package manager console to Add-Migration and then Update-Database.

After updating the database I ran the app to verify my changes. What I saw when my contact list load was that all my seed data had been duplicated. The jest of my seed function was something like this:

To track down the duplication issue the first thing I did was to view the data in the database to make sure the table a primary key set. The Id field was an integer identity column and was the primary key. Next I viewed all the records in the table which looked like this:

Id Name State
0 Eric TN
1 Tommy ND
2 Eric TN
3 Tommy ND

The Id lookup I defined as the first parameter to AddOrUpdate seemed to be my issue. From my tests it seems that AddOrUpdate will always perform an add when trying to match on an identity type column. By changing from c => c.Id to c => c.Name no data is duplicated.

Leave a Reply

Your email address will not be published. Required fields are marked *