.netasp.net-mvcentity-frameworkasp.net-web-api

Entity Framework Many to many Web API Get


I've been looking at a million pages and I feel like this should be trivial but I'm really struggling.

I'm trying to create a .net Web API with Code first and I have two models: Events and Teams. Each event has many teams and each Team does many events.

In my /api/GetEvents request I'm getting the event info fine, but the list of teams associated with that event is null

// GET: api/Events
    public IQueryable<Event> GetEvents()
    {
        return db.Events
    }

Event:

public class Event
{
    public int EventId { get; set; }
    [Required]
    public string EventTitle { get; set; }
    [Required]
    public string EventLocation { get; set; }
    public string EventTicketPrice { get; set; }
    [Required]
    public DateTime EventDateTime { get; set; }
    [Required]
    public ICollection<Team> Teams{ get; set; }
}

Team:

public class Team
{
    [Key]
    public int TeamId { get; set; }
    [Required]
    public string TeamName { get; set; }
    public string Class { get; set; }
    public string TeamLocation { get; set; }
    public string TeamWebsite { get; set; }

    public ICollection<Event> Events { get; set; }
}

I've checked the generated database and the intermediate table is there but its not connecting the many to many relationship. I've attempted querying to tie them together, but there isn't a DbSet to the intermediate table to join to tables. What am I missing?


Solution

  • Try making the collection properties virtual:

    public virtual ICollection<Team> Teams{ get; set; }
    

    And:

    public virtual ICollection<Event> Events { get; set; }
    

    "Virtual" is used by EF to mark navigation properties that it will try to maintain for you, for instance with lazy loading. If you do not mark navigation properties with virtual, you are on your own for ensuring that the target of the navigation has been loaded.