In a real-world scenario, only a limited quantity of a particular item belongs to a particular order. Imagine, you have an order cart containing references to some selected items with their respective ordered quantities. The end result is you got a relationship something like: an order can have many items whereas an item can be part of multiple orders.
By EF Core conventions, in a many-to-many relation, you have two standalone entities and a third entity between them which represents a relationship bridge. In our case, the bridging entity will be the OrderItem
Here we have two reference navigation properties for each side of the relation i.e. Order and Item. Also, we have two foreign key properties i.e. ItemId and OrderId.
For a fully defined relationship, we also have individual collection navigation property of OrderItem on each side of the standalone entities,
We are using an In-Memory database so no migration script is needed for each iterative changes on the database. But, once you have configured all the necessary relationships, create a migration and update your development/production database using dotnet CLI with the following commands,
dotnet ef migrations add ManyToManyRelationship
dotnet ef database update
We can add a GraphQL end-point for adding an item to a particular order. To do that we need an InputGraphTypeType for OrderItem.
As for the end-point, we registered a new mutation field inside GameStoreMutation.cs. The field is simply named addOrderItem,
Newly added OrderItemType is as following,
Newly registered methods from Repository.cs are as following,
I've also threw in an additional field for querying a list of all the OrderItem at once,
Repository code for GetOrderItem is as following,
Last but not least, don't forget to register the newly added graph types with the DI system. Services registration inside ConfigureServices are as followings,
That's all about it. Run the application and try to add an item to a particular order with a mutation like the following illustration,