The database diagram below shows the three tables, with the foreign key links from the Book Author linking table to the other two tables.A linking table like this has foreign keys (FK in the diagram) which link to the primary key(s) (PK in the disgarm) of each end of the relationship – in this case the Book Id of the Book entity and the Author Id of the Author entity.After the test has finished the book “Quantum Networking” has two authors, “Future Person” and “Martin Fowler” Note: The default way of loading data in EF Core is as tracked entities, that is, EF Core takes a copy of the loaded data so that it can detect if any changes have happened since they were loaded.You can turn off tracking by including the method .The second stage, which uses a new instance of the Db Context, uses those primary keys to build a new Book Author linking entity to add to the database.NOTE: The one downside of this approach for my Book/Author example is the setting the Order property, as it should be set to get the correct order of the authors.
Having loaded that book I can use the same code I had in the connected state, that is, I create a new Book Author linking entry linking the Book entity I loaded to the Author entity of “Martin Fowler” and add it to the existing Author Links collection – see lines 32 to 37.
The easiest approach to setting up relationships is by using EF Core’s conventions, which is what I have done. NOTE: You can set the keys, but not the relationships, via attributes.
But if you want to explicitly define the relationships you can, using the . The [Key] and [Order] attributes allow you to define the primary key, but I find the Fluent API is quite clean and easy to understand.
When Save Changes is called on line 24 it finds that the Author Links property of the book instance it loaded has changed.
Because this is a relationship it looks at the entities and finds that there is a new Book Author entity, which it adds to the database, and a author which is already in the database so it doesn’t have to add it.