简体   繁体   中英

Retrieving entities from a one to many relationship (Odata)

Summarizing, I have two main tables: Company and Employees , with a one-to-many relationship between them: employees belongs to a company.

The Company entity has a property called Employees, which allows to get the employees who belongs to the specific Company.

If I type in the browser this URL, it works and I get an employees list:

http://domain.com/DynamicsNAV80/OData/Company('whatever')/Employees

Now, I want to retrieve the employees using a Linq query, how can I do it?

I have tried this:

var dataServiceQuery = (DataServiceQuery<Company>)from comp in _context.Company.Expand(comp => comp.WhseEmployee)
                                                  where comp.Name == "whatever"
                                                  select comp.WhseEmployee;

But this is not working for me.

What does that query return, an error or just not the data your looking for? Im not sure if the syntax for querying Odata is different but this is how i would do it any other time.

              var dataServiceQuery = from comp in _context.Company.Expand("WhseEmployees")
                                     where comp.Name == "whatever"
                                     select comp;

Which version of OData are you using?

If it is V4. You can try following code.

var employees = _context.Company.ByKey("whatever").WhseEmployee;

Please refer to Client Delayed Query

If it is V3. You need to query the company first, and then use LoadProperty to send request to /Company('whatever')/WsheEmployee.

var company = _context.Company.Where(c=>c.Name="whatever").First();
dsc.LoadProperty(company, "WsheEmployee");

Finally I could do with this query:

    var dataServiceQuery = (DataServiceQuery<WhseEmployee>)_context.Company.Where(c => c.Name == companyName)
                                                                           .SelectMany(c => c.WhseEmployee);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM