Referential integrity constraint violation when adding entities with composite primary keys RRS feed

  • Question

  • I am testing a scenario with creation of entities with many-to-many relationship. Let's say we have Persons, Books and BookRatings. Persons and Books have no relationship, but BookRatings has a composite primary key PersonId+BookId. If I have code like this:

          foreach (var person in listPersons)
            foreach (var book in listBooks)
              BookRatings rating = new BookRatings { Rating = 1 };
              rating.Persons = person;
              rating.Books = book;
              _entities.AddLink(person, "BookRatings", rating);
              _entities.AddLink(book, "BookRatings", rating);
              _entities.SetLink(rating, "Persons", person);
              _entities.SetLink(rating, "Books", book);

    then I get the following error:

    "A referential integrity constraint violation occurred: A primary key property that is a part of referential integrity constraint cannot be changed when the dependent object is Unchanged unless it is being set to the association's principal object. The principal object must be tracked and not marked for deletion."

    I've found a thread with a similar problem . The author of that thread came to conclusion: "So unless I'm doing something wrong (hopeful) it seems like to work with many to many over WCF you're either stuck with persisting the entities first than persisting the XREF in two separate calls or not in a batch style call or adding an identity column and dealing with the many to many table yourself."

    I wonder if this was a right conclusion. Is it so that WCF Data Service don't support creation of related entities where one of them has a composite primary key in case all entities are being created?


    Vagif Abilov
    Sunday, November 21, 2010 8:01 PM

All replies

  • Just to make it clear: all elements in listBooks and listPersons collection are also being created in the same batch. So the whole hierarchy of new objects is sent with SaveChanges. And this code works fine with EF.

    Vagif Abilov
    Sunday, November 21, 2010 8:20 PM
  • Could you paste the schema model for us to reproduce this in-house ?
    Bindesh V[MSFT] Community Forum Escalation This posting is provided "AS IS" with no warranties, and confers no rights.
    Monday, February 21, 2011 6:24 AM