1

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?

Ivan Stoev
  • 159,890
  • 9
  • 211
  • 258
Cooky
  • 13
  • 3
  • People tend to close questions like this as a duplicate of [this one](https://stackoverflow.com/q/4660142/861716) because you're the only one who can diagnose this properly. – Gert Arnold Jul 14 '18 at 21:30
  • Agree with above comment. You need to debug, which is object is the null one in your code? – Y.S Jul 15 '18 at 11:12
  • Thanks, I will improve my questions in the future. – Cooky Jul 15 '18 at 13:13

1 Answers1

1

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();
Ivan Stoev
  • 159,890
  • 9
  • 211
  • 258
  • 1
    Thanks, this definitely solved it! Also, thanks for the advice, I didn't know about the different Entity Frameworks and shall endeavour to research my questions better in the future. – Cooky Jul 15 '18 at 13:10