Skip to content
Advertisement

EF Core 5 failing while trying to update a foreign key which is also part of a unique Index

Like the title says, I am trying to update a foreign key and getting below error:

The property ‘Student.APID’ is part of a key and so cannot be modified or marked as modified. To change the principal of an existing entity with an identifying foreign key, first delete the dependent and invoke ‘SaveChanges’, and then associate the dependent with the new principal.

The Student class looks like this:

The StudentPayee looks like this:

And the OnModelCreating method looks like this:

Entity config for StudentPayee:

As you can see the APID is a foreign key and part of the unique index. So, whenever I try to update the APID like below, I get the error. This used to work with Entity Framework 6.

Advertisement

Answer

I ended up using Context.Database.ExecuteSqlRaw(query) to update the foreign key instead of LINQ. Thanks for all your help.

User contributions licensed under: CC BY-SA
5 People found this is helpful
Advertisement