簡體   English   中英

如何使用Entity Framework從通過外鍵鏈接的多個表中獲取所有數據?

[英]How to get all data from multiple tables linked by foreign keys with Entity Framework?

我是Entity Framework的新手,但無法從以下數據庫中獲取所有數據:

在此處輸入圖片說明

我為上面顯示的所有實體創建了控制器,如下所示:

    // Retrieve entire DB
    AareonAPIDBEntities dbProducts = new AareonAPIDBEntities();

    // Get all customers
    [System.Web.Http.AcceptVerbs("GET")]
    [System.Web.Http.HttpGet]
    [System.Web.Http.Route("customer")]
    public IEnumerable<Customer> Default()
    {
        List<Customer> customers = dbProducts.Customers.ToList();
        return customers;
    }

    //Get customer by ID
    [System.Web.Http.AcceptVerbs("GET")]
    [System.Web.Http.HttpGet]
    [System.Web.Http.Route("customer/{id}")]
    public Customer getById(int id = -1)
    {
        Customer t = dbProducts.Customers
                               .Where(h => h.customerID == id)
                               .FirstOrDefault();
        return t;
    }

現在,我很難找到如何通過customerID檢索表PropertyLeaseContract由外鍵鏈接的所有數據庫數據。 我正在嘗試獲取一個JSON響應,其中獲取了customersID和值,其中是來自鏈接的LeaseContractProperty的對象數組。

希望有人能幫忙。

提前致謝!

假設您的關系在DbContext配置中正確設置,並且您在實體類中具有適當的導航屬性,則它應如下所示工作:

public Customer getById(int id = -1)
{
    Customer t = dbProducts.Customers
            .Where(h => h.customerID == id)
            .Include(x => x.PropertyLeaseContracts)
              .ThenInclude(x => x.LeaseContract)
            .Include(x => x.PropertyLeaseContracts)
              .ThenInclude(x => x.Property)
            .FirstOrDefault();
    return t;
}

為此,您的客戶類需要具有PropertyLeaseContract的Collection屬性並將其設置為OneToMany關系。 並且您的PropertyLeaseContract類需要具有LeaseContract和Property類型的Properties,並且必須正確設置。

編輯:上面的代碼僅在@TanvirArjel提到的Entity Framework Core中有效。 在實體框架中,完整代碼應如下所示:

public Customer getById(int id = -1)
{
    Customer t = dbProducts.Customers
            .Where(h => h.customerID == id)
            .Include(x => x.PropertyLeaseContracts.Select(plc => plc.LeaseContract))
            .Include(x => x.PropertyLeaseContracts.Select(plc => plc.Property))
            .FirstOrDefault();
    return t;
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM