1 Replies - 5174 Views - Last Post: 13 August 2012 - 02:50 PM

#1 mvcwannab  Icon User is offline

  • New D.I.C Head

Reputation: 0
  • View blog
  • Posts: 17
  • Joined: 26-July 12

MVC 4 Database Migration - Seeding data

Posted 13 August 2012 - 10:36 AM

I have a database that I'm trying to seed using automatic migration. The creation of the database and tables are working, however when trying to load data into a many-to-many table, I get a record duplication for each time the item from one table is "attached" to the parent table.
Example:
Person => Child
Child => Person

Tables:
Person
Child -> PersonID FK
PersonChildren -> PersonID / ChildID

Adding Child to Person creates a new duplicate entry in the child table for each parent person.
...
IList<Person> people = new IList<Person> { ... }
foreach (Person curPerson in people)
{
curPerson.Children = new IList<Child> { ... }
context.Person.AddOrUpdate(curPerson);
}
context.SaveChanges();
...


between the elipses I am adding the specific information for each class, which works. The result is table Person containing 2 entries (as expected) and the child table consisting of 4 (2 are expected). Two children to two parents, same two children have the same two parents (mom and dad in this case). The join table has the 4 entries that are also expected ({PersonID=1, ChildID=1}, {PersonID=1, ChildID=2} .... )

I have tried this with finding the ID of the object that I want to add to parent
...
curPerson.Children = dbRepo.Find(child => child.ID == 1);
context.Person.AddOrUpdate(curPerson);
...


This causes error
System.InvalidOperationException: An entity object cannot be referenced by multiple instances of IEntityChangeTracker.


when running the seed method.
I am using update-database -verbose when migrating new changes instead of relying on database migration on load.

Is This A Good Question/Topic? 0
  • +

Replies To: MVC 4 Database Migration - Seeding data

#2 mvcwannab  Icon User is offline

  • New D.I.C Head

Reputation: 0
  • View blog
  • Posts: 17
  • Joined: 26-July 12

Re: MVC 4 Database Migration - Seeding data

Posted 13 August 2012 - 02:50 PM

If it helps any, when I take out the addition of the child object to the person object, the ID's are populated, and the objects can be referenced in code if I populate the join table manually. This is not feasible as this has a potential to be the case every time someone adds a child to a person.

Any directional help would be appreciated as well. I have been all over the web trying to figure this issue out with no luck.
Was This Post Helpful? 0
  • +
  • -

Page 1 of 1