I am trying to built an API that will return all the data for a server. A server can have multiple endpoints and they are stored in separate table with many-to-many relationship.
I have 3 tables:
Servers
table contains all the server detailsApplications
table that contains application namesapplication_endpoint
table that contains foreign keys to both tablesServers
andApplications
Here is my database model:
Here are my models:
public class Servers
{
public int id { get; set; }
public string server_name { get; set; }
public string alias { get; set; }
public string ip_address { get; set; }
public Status status { get; set; }
public virtual ICollection<Application_endpoints> endpoint { get; set; }
}
public class Application_endpoints
{
public int id { get; set; }
public int? server_id { get; set; }
[ForeignKey("server_id")]
public Servers server { get; set; }
public int? application_id { get; set; }
[ForeignKey("application_id")]
public Applications application { get; set; }
}
public class Applications
{
public int id { get; set; }
public string app_name { get; set; }
}
public class ServerDbContext : DbContext
{
public DbSet<Applications> Applications { get; set; }
public DbSet<Application_endpoints> Application_endpoints { get; set; }
public DbSet<Servers> Servers { get; set; }
}
In my Api Controller, I have created HttpGet
method that will query database and return data for each server. Here is simple API for GET:
private ServerDbContext _context;
public ServersController (ServerDbContext context)
{
_context = context;
}
// GET: api/values
[HttpGet]
public JsonResult Get()
{
var servers = _context.Servers
.Include(endpoint => endpoint.endpoint)
.ToList();
return Json(servers);
}
Now when I make a get request, I get data back from the database, however the application
object in below JSON is returned null. I am trying to figure it out how to add left join in my above query so I can get application name from applications table.
{
"id": 6,
"server_name": "server1",
"alias": "",
"ip_address": "192.168.1.7",
"endpoint": [
{
"id": 23,
"server_id": 6,
"application_id": 10,
"application": null
}
]
}
Any help is really appreciated. :)