Entity Framework: A referential integrity constraint violation on many to many relationship

后端 未结 6 1280
一向
一向 2020-12-15 15:27

Hey I have an application with a bunch of inproc caching and entity framework. When I want to write an update to an entity I reattach the cached copy. I track all things I\'

6条回答
  •  慢半拍i
    慢半拍i (楼主)
    2020-12-15 16:22

    The error could occur for the one-to-many relationship between Person and Location you apparently have in your model in addition to the many-to-many relationship. For example the following code would throw the exception:

    using (var context = new MyContext())
    {
        var person = new Person
        {
            CurrentLocationId = 1,
            CurrentLocation = new Location { Id = 2 }
        };
        context.People.Attach(person); // Exception
    }
    

    "The property values that define the referential constraints" are the foreign key property value CurrentLocationId and the primary key value CurrentLocation.Id. If those values are different the exception is thrown. (Having CurrentLocation as null though is allowed.)

    In my opinion this exception can only be thrown for foreign key associations because only for this type of association you have properties that define referential constraints at all in your model. It cannot be thrown for independent associations. Since every many-to-many relationship is an independent association (no foreign key property in the model) my guess is that the error is not related to your many-to-many relationship, but to the one-to-many.

提交回复
热议问题