2016-02-13 64 views
2

我想構建一個API,它將返回服務器的所有數據。服務器可以有多個端點,並且它們存儲在具有多對多關係的單獨表格中。實體框架7 3表連接的Lambda表達式

我有3個表:

  • Servers表包含所有服務器的詳細信息
  • Applications表包含應用程序的名稱
  • application_endpoint表包含外鍵兩個表ServersApplications

這裏是我的數據庫模型:

enter image description here

這裏是我的模型:

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 
    } 
    ] 
} 

任何幫助真的很感激。 :)

+2

你試過'.Include(endpoint => endpoint.endpoint.Select(e => e.application))'?爲什麼我rember這是你如何做EF6 –

回答

1

你需要改變你的查詢條件包含:

.Include(endpoint => endpoint.endpoint) 

.Include(s => s.endpoint.Select(e => e.application)) 

或者你可以使用字符串路徑作爲

.Include("endpoint.application") 
+0

Vittore和omar.ballerani,我只是嘗試了你的建議,但是,我得到一個例外,當我做出請求。這裏是例外情況:'附加信息:無法投射類型爲'Remotion.Linq.Clauses.Expressions.SubQueryExpression'的對象來鍵入'System.Linq.Expressions.MemberExpression'. – Ray

+0

@vittore - 上述查詢將引發異常我的情況是「確保你沒有無限循環或無限遞歸」。我已經在這裏展示了db圖和完整的查詢:http://stackoverflow.com/questions/42453123/get-selected-values-after-joining-multiple-tables-in-entity-framework-6-using-la Could你請看看!? – sandiejat

2

全部,

謝謝你引導我走向正確的道路。我做了快速谷歌搜索,它看起來EF7中的語法已經改變。下面的工作:)

var servers = _context.Servers 
      .Include(e => e.endpoint).ThenInclude(a => a.application) 
      .ToList();