Seeding a Many to Many With Entity Framework and C# Dynamic

In the previous post, we created a single table (speakers) with Entity Framework Code First from a JSON file with Visual Studio 2015.  Now we will add a sessions table that has a many to many relationship to the speakers table.  That is, speakers can have multiple sessions and sessions can have multiple speakers.  We do that but simply creating another entity (sessions) and add to it a List of speakers and then adding to the existing speakers table a list of sessions.  The new table (models) look as follows.

GitHub Repo: https://github.com/pkellner/EntityFrameworkSeedFromJSON

Then,  we need to add sessions data (from the JSON file) but when we add the sessions, we need to add the speakers records associated with each session.  That is, we simply populate the List of sessions in the speaker model to make this happen.

One problem we ran into was that EF Code First really wants to control the Id of each record and since in our original data, the many to many relationship was maintained by original primary keys, we need to bring along the original speaker Id.  We do this by simply adding an extra column to the speaker model called PictureId and set that as an attribute (column) of the speaker table.  Then, we can use that to search the speakers table for the existing speakers.

The code below (and also in the GitHub repo) basically does this for us.  It again uses NewtonSoft.JSON as well as the dynamic type in c# to get the job done.

To test the results, in Program.cs we put some simple loops and Console Write’s to show.

HTH’s

About Peter Kellner

Peter is a software professional specializing in mobile and web technologies. He has also been a Microsoft MVP for the past 7 years. To read more about Peter Kellner and his experience click here. For information about how Peter Kellner might be able to help you with your project click here.

Follow me:


Comments

  1. Thanks for sharing. Do you think this many-to-many pattern will work on multiple levels.

    Speakers can have multiple sessions and sessions can have multiple speakers, and multiple speakers can have student speakers?

    A coda. I implemented many-to-many for as-built medical device bill-of material traceability but views reporting from the bottom up could often times be contaminated with unwanted records. Somewhat self-inflicted because of optimizing for performance on huge data sets top 1000 finished goods x has 5 components who has 3 components – easy with unique lot numbers 1 to many – but with Lot Numbers plus Serial Numbers much harder. I could solve by enforcing unique lot / serial numbers, but FDA domains often prefer maintaining vendor lot numbers across supply chain manufactures to help traceability recalls.

    Btw. Your speaker table will ahead of mine ūüôā
    http://gdgdevfest2015.com

Follow

Get every new post delivered to your Inbox

Join other followers: