[英]How to get all data from multiple tables linked by foreign keys with Entity Framework?
I'm new to Entity Framework and I'm having trouble to fetch all data from the following database: 我是Entity Framework的新手,但无法从以下数据库中获取所有数据:
I created controllers for all of the entities shown above like this: 我为上面显示的所有实体创建了控制器,如下所示:
// 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;
}
Now I'm having trouble finding out how to retrieve all of the database data linked by foreign keys in table PropertyLeaseContract
by customerID
. 现在,我很难找到如何通过
customerID
检索表PropertyLeaseContract
由外键链接的所有数据库数据。 I'm trying to get a JSON response where I get the customersID
and values, therein an array of objects from the linked LeaseContract
and Property
. 我正在尝试获取一个JSON响应,其中获取了
customersID
和值,其中是来自链接的LeaseContract
和Property
的对象数组。
Hope someone can help. 希望有人能帮忙。
Thanks in advance! 提前致谢!
Assuming your relations are properly set up in the DbContext Configuration and you have appropriate Navigation Properties in your Entity Classes it should work something like this: 假设您的关系在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;
}
For that to work your Customer Class needs to have a Collection Property of PropertyLeaseContract and be setup as a OneToMany Relation. 为此,您的客户类需要具有PropertyLeaseContract的Collection属性并将其设置为OneToMany关系。 And your PropertyLeaseContract class needs to have Properties of type LeaseContract and Property and also be setup correctly.
并且您的PropertyLeaseContract类需要具有LeaseContract和Property类型的Properties,并且必须正确设置。
EDIT: The above code works only in Entity Framework Core as mentioned by @TanvirArjel. 编辑:上面的代码仅在@TanvirArjel提到的Entity Framework Core中有效。 In Entity Framework Full code should look something like this:
在实体框架中,完整代码应如下所示:
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.