Query items inside collection inside collection

asp.net c# entity-framework entity-framework-core linq

Question

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?

1
1
7/15/2018 12:28:02 PM

Accepted Answer

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();
1
7/15/2018 12:27:26 PM


Related Questions





Related

Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow