EF Core 5 many-to-many disconected add/remove without join entity class

Diego Torres 1 Reputation point
2021-01-30T09:27:12.827+00:00

EF Core 5 introduced many-to-many by convention, we only need to add the collection navigation property on each side and it works.
I know I can query one side of the relationship, add it to the collection property and save it, but this requires an extra database trip.
Is it possible to add or remove using disconnected entities under this configuration?
I am aware that adding a intermediate class and mapping the join table would allow me to do this, I am asking about the many-to-many by convention way.

Entity Framework Core
Entity Framework Core
A lightweight, extensible, open-source, and cross-platform version of the Entity Framework data access technology.
695 questions
0 comments No comments
{count} votes

1 answer

Sort by: Most helpful
  1. Daniel Zhang-MSFT 9,611 Reputation points
    2021-02-01T06:13:50.197+00:00

    Hi DiegoTorres-0892,
    There is a way to directly manipulate relationships for a many-to-many association but it requires to go down to the ObjectContext and its RelationshipManager which is pretty advanced and tricky.
    The usual and straight-forward way to add and remove relationship entries to/from a many-to-many association is by just adding items to and removing items from the collections while the entities are attached to the context. EF's change tracking mechanism will recognize the changes you have done and generate the appropriate INSERT, UPDATE and DELETE statements when you call SaveChanges.
    EF team will include a feature where we don't need to create a joining entity for many-to-many relationships in future. More discussion on GitHub you can refer to.
    Best Regards,
    Daniel Zhang


    If the response is helpful, please click "Accept Answer" and upvote it.

    Note: Please follow the steps in our documentation to enable e-mail notifications if you want to receive the related email notification for this thread.

    0 comments No comments