Tom Yee
Tom Yee

Reputation: 99

How do I Get Asp.net web api to join 2 tables (1 to many relation)

I am new to Web Api and just trying to learn by playing with different examples. I am completely stuck on trying to write a Get request to return a complex type. I have 3 entities, 1 of the entities has a list of another entity, So I am trying to figure out how to return the data from within both.

I looked at some examples on stack overflow, that showed to use the .Include linq statement, but when I try that, I am getting compiler errors (type argument cannot be inferred.

Basically, I have a class of Players, Teams and Specialties. Once I get this working, I am planning on writing an angular project. The specialties table is a multiselect for a given player.

Here is what I have written so far

public class Player
{
    public int Id { get; set; }
    public string FirstName { get; set; }
    public string LastName { get; set; }
    public int JerseyNo { get; set; }
    public DateTime DateAquired { get; set; }
    public string Bio { get; set; }

    [ForeignKey("TeamID")]
    public virtual Team Team { get; set; }
    public virtual IEnumerable<Specialty> Specialites { get; set; }

}
public class Specialty
{
    public int Id { get; set; }
    public string Speciality { get; set; }


    public virtual Player Player { get; set; }

}


public class Team
{
    public int Id { get; set; }
    public string TeamName { get; set; }

    public virtual Player Player { get; set; }
}



public class dbContext :DbContext
{
    public DbSet<Player> Players { get; set; }
    public DbSet<Team> Teams { get; set; }
    public DbSet<Specialty> Specialties { get; set; }


    protected override void OnConfiguring(DbContextOptionsBuilder builder)
    {
        builder.UseSqlServer(@"Server=(localdb)\mssqllocaldb;Database=Test;Trusted_Connection=True;");
    }
}

When I created the database using migrations, it looks how I want it to, but cannot figure out Web Api's joins to get the data from my specialties table. The .Include cannot recognize any value I enter as parameters

 private dbContext db = new dbContext();
    // GET: api/values
    [HttpGet]
    public IEnumerable<Player> Get()
    {
        var teams = db.
            Players
            .Include("Specialties")

            .Select(p=> new Player

Upvotes: 0

Views: 1971

Answers (1)

Michael
Michael

Reputation: 3631

Looks like this an Entity Framework question.

Try if you can get this to work, for debugging purpose:

var teams = db.Players.ToList();
foreach (var player in teams)
{
    // Force lazy loading of Specialities property
    player.Specialities.ToList();
}

If this doesn't work, it looks like EF cannot figure out the mapping to the database.

Upvotes: 1

Related Questions