asp.net-core-mvc

Get property from other side of many to many relationship ASP.NET Core 6 MVC


In the MoviesController Details method, I would like to show the collection that movie belongs to. I figure I could put it in a ViewData to display on the page. I added the MovieCollections and Collections to the Movie object, and I can see the collection in the debugger, but the intellisense won't let me put it in a ViewData.

In other words, it won't let me do this...

ViewData["Collection"] = movie.MovieCollections.Collection.Name;

enter image description here

Here is the LINQ

movie = await _context.Movie
    .Include(m => m.Cast)
    .Include(m => m.Crew)
    .Include(m => m.MovieCollections)
        .ThenInclude(m => m.Collection)
    .FirstOrDefaultAsync(m => m.MovieId == id); 

Models with relevant properties:

public class Movie
{
    public int Id { get; set; }

    //The movieID from TMDB. 
    public int MovieId { get; set; }
    public ICollection<MovieCollection> MovieCollections { get; set; } = new HashSet<MovieCollection>();
}

public class MovieCollection
{
    public int Id { get; set; }
    public int CollectionId { get; set; }
    public int MovieId { get; set; }

    public virtual Collection Collection { get; set; }
    public virtual Movie Movie { get; set; }
}

public class Collection
{
     public int Id { get; set; }
     public string Name { get; set; }
     public string Description { get; set; }

     public ICollection<MovieCollection> MovieCollections { get; set; } = new HashSet<MovieCollection>();
} 

Solution

  • The MovieCollections is type of ICollection,you need read the property in ICollection like below:

    ViewData["CollectionNames"] = movie.MovieCollections.Select(mc => mc.Collection.Name).ToList();
    

    Then you can display the name like below:

    @if (ViewData["CollectionNames"] is List<string> collectionNames && collectionNames.Any())
    {
        <ul>
            @foreach (var name in collectionNames)
            {
                <li>@name</li>
            }
        </ul>
    }
    else
    {
        <span>No collections</span>
    }