繁体   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