我想構建一個API,它將返回服務器的所有數據。服務器可以有多個端點,並且它們存儲在具有多對多關係的單獨表格中。實體框架7 3表連接的Lambda表達式
我有3個表:
Servers
表包含所有服務器的詳細信息Applications
表包含應用程序的名稱application_endpoint
表包含外鍵兩個表Servers
和Applications
這裏是我的數據庫模型:
這裏是我的模型:
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; }
}
在我的API控制,我創建HttpGet
方法,將查詢數據庫中,每個服務器返回的數據。下面是簡單的API爲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);
}
現在,當我做一個GET請求,我在下面的JSON則返回null獲取數據從數據庫返回的,但是application
對象。我想弄清楚如何在我的上面的查詢中添加左連接,以便我可以從應用程序表中獲取應用程序名稱。
{
"id": 6,
"server_name": "server1",
"alias": "",
"ip_address": "192.168.1.7",
"endpoint": [
{
"id": 23,
"server_id": 6,
"application_id": 10,
"application": null
}
]
}
任何幫助真的很感激。 :)
你試過'.Include(endpoint => endpoint.endpoint.Select(e => e.application))'?爲什麼我rember這是你如何做EF6 –