Cooky
Cooky

Reputation: 13

Query items inside collection inside collection

I have the following classes in my .net core 2.0-mvc app:

public class TeamMatch
{
    public int ID { get; set; }
    public virtual ICollection<IndividualMatch> Matches { get; set; }

    public IEnumerable<Map> GetMaps()
    {
        var list = new List<IndividualMatch>();
        list.AddRange(Matches.GroupBy(m => m.MatchMap.ID).Select(u => u.First()));
        return list.Select(m => m.MatchMap);
    }
}

public class IndividualMatch
{
    public int ID { get; set; }
    public Map MatchMap { get; set; }
}
public class Map
{
    public int ID { get; set; }
    public string Name { get; set; }
}

And this gets passed from the Controller to the View:

public IActionResult Index()
{
    var dat = _context.TeamMatches.Include(tm => tm.Matches).ToList();
    return View(dat);
}

I get a NullReferenceException when calling TeamMatch.GetMaps() in that View. Specifically in this line, it is supposed to give me an array of unique Maps in all of the IndividualMatches:

list.AddRange(Matches.GroupBy(p => p.MatchMap.ID).Select(g => g.First()));

I assume I somehow need to get "1 level deeper" than just the IndividualMatch that I've included there. How do I accomplish this?

Upvotes: 1

Views: 268

Answers (1)

Ivan Stoev
Ivan Stoev

Reputation: 205619

I assume I somehow need to get "1 level deeper" than just the IndividualMatch that I've included there.

That's correct.

How do I accomplish this?

The answer depends on what Entity Framework ae you targeting - EF6 or EF Core, because they use different mechanisms for including multiple levels of related data. That's why it's important to include such information in the question.

Assuming that you use EF Core (based on "my .net core 2.0-mvc app"), Including multiple levels is achieved with chaining Include / ThenInclude expressions:

var dat = _context.TeamMatches
    .Include(tm => tm.Matches)
        .ThenInclude(m => m.MatchMap) // <--
    .ToList();

Upvotes: 1

Related Questions