alternate of join in OData Service using linq

2019-04-16 14:51发布

问题:

I want to join two tables in LINQ, my query is some thing like

SELECT        mfg.MfgName
FROM            MasterProductStaging AS mps INNER JOIN
                         Mfg AS mfg ON mps.MfgID = mfg.MfgID
WHERE        (mps.MasterProductStagingID = 345345)

Now in LINQ, I solve this problem using two different queries

    var test = (from d in DataContext.MasterProductStagings
                                        where d.MasterProductStagingID == Convert.ToInt32(Request.QueryString["MPSID"])
                                        select d.MfgID).FirstOrDefault();

var data = (from d in DataContext.Mfgs
                                        where d.MfgID == test.ToString()
                                        select d).FirstOrDefault();

The tables doesn't have any relation in emdx Model. Now I to get my desired data in a single query.

回答1:

OData protocol doesn't support JOIN, but you can still retrieve related data in a single request. Here are a couple of examples from OData.org:

http://services.odata.org/OData/OData.svc/Categories(1)/$links/Products

Identifies the set of Products related to Category 1. Is described by the Navigation Property named "Products" on the "Category" Entity Type in the associated service metadata document.

http://services.odata.org/OData/OData.svc/Products(1)/$links/Category

Identifies the Category related to Product 1. Is described by the Navigation Property named "Category" on the "Product" Entity Type in the associated service metadata document.

This should give you a basic idea of OData links. And if you want to use LINQ with OData, you should first create a proxy class using WCF Data Services. Then you can LINQ queries, but bear in mind that they are more limited than Entity Framework - for example they don't have support for JOIN, but support an alternative way of retrieving related data, e.g.:

var ordersQuery = from o in context.Orders.Expand("Order_Details")
    where o.CustomerID == "ALFKI" 
    select o;