Notice: Undefined offset: 0 in /home/canofcod/public_html/wp-content/themes/FreshAppCore/functions.php on line 55

Notice: Trying to get property 'ID' of non-object in /home/canofcod/public_html/wp-content/themes/FreshAppCore/functions.php on line 55

Can Of Code

ASP Entity Framework Many to Many not working

i’ve been working on a simple book website using ASP MVC.  I have a Book class and an Author class. Each book can have one or more Authors and each Author can have one or more books.

Many to Many incorrect in the database

The first issue I came across was that the database was being created without a lookup table as should be the case with a many to many relationship. instead it added a bookId to the Author table. This would mean that duplicate author records would exist for authors with more than one book.

To fix this (thanks to @TheRealDuckboy) I just needed to add a List of books to the Author object! I only had a Author list in the Book object which confused Entity Framework.

Correct database layout, hurrah?

After solving my borked many to many relationship I stumbled across my next issue. It was time to list the authors of the Book object in my view. The Book’s Authors property was null. After checking the database I saw that the data was there and the relationship was valid.

The problem was with how I represented the collection in the Model.  I naively bashed out the following:

 

public List<Book> Authors { get; set;}

 

After some googling i saw that people were using a ICollection for their lists. Its always a good idea to use a generic interface so more fool me.

 

public ICollection<Book> Authors { get; set; }

 

So I ran “update-database” to do the code first migration and started running. The Authors property was still null!

What I then found was that I was missing the “virtual” keyword.

 

public virtual ICollection<Book> Authors { get; set; }

 

It worked! This Stackoverflow answer suggests that the collection can’t be lazy loaded (loaded when first accessed) unless its virtual.

Leave a Reply

Your email address will not be published. Required fields are marked *