efcore icon indicating copy to clipboard operation
efcore copied to clipboard

[EF Core 8] [Breaking Change] - error on working with explicit many-to-many relations with OnDelete.Restrict

Open Gretam11 opened this issue 3 years ago • 19 comments

Description

I'm currently migrating our project to the latest .NET and EF Core version (8), and I stumbled across the narrow, undocumented breaking change. When you have many-to-many relation (Authors<->Books) with explicit intermediate table (BookAuthors), and you defined relations with OnDelete.Restrict action, then SaveChanges() throws an error if you try to modify list of linked entities (BookAuthors) through the root entity (Book).

Example

Entities:

public class Author
{
    public long Id { get; set; }
    public string Name { get; set; }
    public List<BookAuthor> BookAuthors { get; set; }
}

public class Book
{
    public long Id { get; set; }
    public string Name { get; set; }
    public List<BookAuthor> BookAuthors { get; set; }
}

public class BookAuthor
{
    public long BookId { get; set; }
    public long AuthorId { get; set; }
    public Book Book { get; set; }
    public Author Author { get; set; }
}

Model config:

modelBuilder.Entity<BookAuthor>().HasKey(x => new { x.AuthorId, x.BookId });

modelBuilder.Entity<BookAuthor>()
    .HasOne<Author>(x => x.Author)
    .WithMany(x => x.BookAuthors)
    .OnDelete(DeleteBehavior.Restrict);

modelBuilder.Entity<BookAuthor>()
    .HasOne<Book>(x => x.Book)
    .WithMany(x => x.BookAuthors)
    .OnDelete(DeleteBehavior.Restrict);

Actual operation:

var book = await dbContext.Books
                .Include(x => x.BookAuthors)
                .FirstAsync();

book.BookAuthors.RemoveAt(0);

await dbContext.SaveChangesAsync(); // error is thrown here

Exception:

Unhandled exception. System.InvalidOperationException: The property 'BookAuthor.BookId' 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.
   at Microsoft.EntityFrameworkCore.ChangeTracking.Internal.NavigationFixer.ConditionallyNullForeignKeyProperties(InternalEntityEntry dependentEntry, InternalEntityEntry principalEntry, IForeignKey foreignKey)
   at Microsoft.EntityFrameworkCore.ChangeTracking.Internal.NavigationFixer.NavigationCollectionChanged(InternalEntityEntry entry, INavigationBase navigationBase, IEnumerable`1 added, IEnumerable`1 removed)
   at Microsoft.EntityFrameworkCore.ChangeTracking.Internal.InternalEntityEntryNotifier.NavigationCollectionChanged(InternalEntityEntry entry, INavigationBase navigationBase, IEnumerable`1 added, IEnumerable`1 removed)
   at Microsoft.EntityFrameworkCore.ChangeTracking.Internal.ChangeDetector.DetectNavigationChange(InternalEntityEntry entry, INavigationBase navigationBase)
   at Microsoft.EntityFrameworkCore.ChangeTracking.Internal.ChangeDetector.LocalDetectChanges(InternalEntityEntry entry)
   at Microsoft.EntityFrameworkCore.ChangeTracking.Internal.ChangeDetector.DetectChanges(IStateManager stateManager)
   at Microsoft.EntityFrameworkCore.ChangeTracking.ChangeTracker.DetectChanges()
   at Microsoft.EntityFrameworkCore.DbContext.TryDetectChanges()
   at Microsoft.EntityFrameworkCore.DbContext.SaveChangesAsync(Boolean acceptAllChangesOnSuccess, CancellationToken cancellationToken)
   at Program.Main() in D:\projects\EF8M2MUpdateError\EF8M2MUpdateError\Program.cs:line 109
   at Program.<Main>()

Versions information

EF Core version: 8.0.0 Database provider: ANY Target framework: .NET 8.0

Additional information

Considering that normal one-to-many relations update with OnDelete.Restrict would also fail in such scenario (with clearer message though: The association between entity types 'Book' and 'Author' has been severed, but the relationship is either marked as required or is implicitly required), probably, the behavior above is correct, and it was wrongly working in EF Core v7. But I decided to create a ticket anyway, maybe it'll help someone who also stumbles across the same issue (since it's kind of a breaking change).

Reproduction repository

Here you can check the minimal project where this bug is reproduced (link). You can also change package versions back to EF.* v7 to check that it wasn't the case in v7.

Gretam11 avatar Nov 22 '23 00:11 Gretam11

Note for triage: everything seems to be by-design here.

ajcvickers avatar Nov 27 '23 12:11 ajcvickers

We also ran into this same breaking issue on our 7 --> 8 upgrade

ADNewsom09 avatar Nov 27 '23 21:11 ADNewsom09

We found this problem after upgrading our project from EF Core 7 to EF Core 8. Hope, the code mentioned by @Gretam11 is corrent in EF Core 7 and also corrent in EF Core 8. Even if it is not purely clean it became usual.

This breaking change (if by-design for triage) is not mentioned at Breaking changes in EF Core 8.0.

jirikanda avatar Nov 29 '23 15:11 jirikanda

Why the code is correct? The same code is mentioned in the Severing a relationship chapter of the documentation.

Severing a relationship now works only for DeleteBehaviors Cascade and ClientCascade. For all other DeleteBehavios the change tracker throws an exception. The exceptions say we cannot change or modify the value of the (composed) primary key, but we are not trying to do it, we want to delete the entity representing the many-to-many relationship.

The only workaround I found is to registrer entities to be removed prior to removing them from the collection.

dbContext.RemoveRange(book.BookAuthors);
book.BookAuthors.Clear();

jirikanda avatar Nov 30 '23 08:11 jirikanda

I also have this regression but only on join tables with payload.

It seems that just declaring the relationships as Cascade in the EF model is another possible workaround. You don't have to actually apply any change to the database tables. Ugly but it works.

ostracoder avatar Nov 30 '23 10:11 ostracoder

Hey @ajcvickers @AndriySvyryd , when can we expect this to be released for 8.0? Our codebase is heavily affected by this and we are trying to plan the update.

triforcely avatar Jan 03 '24 08:01 triforcely

@triforcely The milestone is 8.0.2, so Feb 2024 or use the daily build

ErikEJ avatar Jan 03 '24 08:01 ErikEJ

Thank you @ErikEJ . When can we expect it to arrive in 8.0 daily builds? AFAIK it is not yet merged to 8.0 release branch.

triforcely avatar Jan 03 '24 09:01 triforcely

@triforcely There are no "8.0" daily builds, use the daily builds of the main branch as described in the docs here: https://github.com/dotnet/efcore/blob/main/docs/DailyBuilds.md

ErikEJ avatar Jan 03 '24 09:01 ErikEJ

Why is this closed if the fix doesn't come until version 8.0.2?

daemons88 avatar Jan 21 '24 14:01 daemons88

@daemons88 Because all the work is done and the fix is now ready to ship with 8.0.2.

ajcvickers avatar Jan 21 '24 14:01 ajcvickers

If you need it now you can use the nightly builds.

ADNewsom09 avatar Jan 21 '24 14:01 ADNewsom09

Okay, thanks for your answers!

daemons88 avatar Jan 22 '24 12:01 daemons88

Will the fix also work if the entity has a composite key with references to the same table? I am having the same issue with the following table:

    public class RoleInRole
    {
        [Key, Column(Order = 0)]
        public int RoleId { get; set; }

        public Role Role { get; set; }

        [Key, Column(Order = 1)]
        public int InRoleId { get; set; }

        public Role InRole { get; set; }

        public RoleAccess Allow { get; set; }
    }

t00 avatar Jan 31 '24 23:01 t00

@ajcvickers When do you plan to release version 8.0.2

stephanmo avatar Feb 07 '24 06:02 stephanmo

Would like to know the same! This "issue" is affecting a solution of mine, but there is no daily build with this fix available, so I'm also eagerly awaiting the official release of 8.0.2 :)

LennardF1989 avatar Feb 13 '24 12:02 LennardF1989

@LennardF1989 The latest daily build contains this fix. If you are seeing otherwise, then please open a new issue and attach a small, runnable project or post a small, runnable code listing that reproduces what you are seeing so that we can investigate.

ajcvickers avatar Feb 13 '24 12:02 ajcvickers

@LennardF1989 Daily build

ErikEJ avatar Feb 13 '24 12:02 ErikEJ

That's an EFCore 9 version, no? I would like to stick to the 8.x range :) The dotnet8 feed doesn't go further than 8.0.0.

However, I just tried to workaround mentioned by @jirikanda and can confirm that first running a Remove/RemoveRange on the DBContext prior to removing it from a navigation property does the trick as well!

LennardF1989 avatar Feb 13 '24 12:02 LennardF1989