2015-09-07 65 views
0

我想在兩個表上實現內部連接查詢opportunityProducts和Products我應該在我的MVC Web API服務中返回Iqueryable元素。但是從下面,我無法獲得結果,因爲它會導致轉換錯誤。使用IQueryable加入LINQ

public IQueryable<OpportunityProducts> GetProductsByShipID(int id) 
{ 
    IQueryable<OpportunityProducts> oppProductss = 
        from c in db.OpportunityProducts 
        from p in db.Products 
        where p.ProductID == c.ProductID 
        select new { c.Quantity,c.ProductDesc,c.RemainingQuantity, p.QtyInHand}; 
    return oppProductss; 
    } 
+0

你的變量是'IQueryable '但你用這行'new {c.Quantity,c.ProductDesc,c.RemainingQuantity,p.QtyInHand}'返回anonymouse對象'你能說你真的想做什麼? –

+0

你不應該返回一個匿名類型。您必須選擇'OpportunityProducts'的'c'變量或者返回一個新類型,該類型也包含兩者的屬性。 –

回答

1

您需要填寫您想返回的Type而不是返回匿名類型。這裏既然你是查詢​​,我想你沒有QtyInHand屬性。因此,您可以完全返回一個新類型或添加此屬性。:-

IQueryable<ResultantProducts> oppProductss = 
        from c in db.OpportunityProducts 
        from p in db.Products 
        where p.ProductID == c.ProductID 
        select new ResultantProducts 
          { 
           Quantity = c.Quantity, 
           ProductDesc = c.ProductDesc, 
           RemainingQuantity = c.RemainingQuantity, 
           QtyInHand = p.QtyInHand 
          }; 
+0

爲什麼你認爲'OpportunityProducts'也有'QtyInHand'屬性? –

+1

@TimSchmelter - 是的,你是對的!糾正。謝謝。 –

+0

我在執行我的查詢時遇到了一個問題「實體無法在LINQ to Entities查詢中構造」。 –

0

我在代碼中看到一個錯誤。您應該返回OpportunityProducts類型的對象,我的意思是:

public IQueryable<OpportunityProducts> GetProductsByShipID(int id) 
    { 
     IQueryable<OpportunityProducts> oppProductss = from c in db.OpportunityProducts 
       from p in db.Products 
       where p.ProductID == c.ProductID 
       select new OpportunityProducts // <---- THIS! 
       { 
        Quantity = c.Quantity, 
        ProductDesc = c.ProductDesc, 
        RemainingQuantity = c.RemainingQuantity, 
        QtyInHand = p.QtyInHand 
       }; 
     return oppProductss; 
    } 

我希望它可以幫助您。

問候,

胡里奧

+1

同樣的問題在這裏:爲什麼你認爲'OpportunityProducts'也有一個屬性'QtyInHand'? –

0

我想你可以創建一個所有屬性的類名爲ResultProducts(在原始表相同的數據類型(可爲空也需要把)),你想要得到的東西。然後你可以返回那個對象。

public class ResultProducts 
    { 

      public int Quantity { get; set; } 
      public string ProductDesc { get; set; } 
      public int RemainingQuantity { get; set; } 
      public int QtyInHand { get; set; } 
    } 

public IQueryable<ResultProducts> GetProductsByShipID(int id) 
     { 
      var oppProductss =from c in db.OpportunityProducts 
           from p in db.Products 
           where p.ProductID == c.ProductID 
           select new ResultProducts() 
           { 
           Quantity =c.Quantity, 
           ProductDesc= c.ProductDesc, 
           RemainingQuantity=c.RemainingQuantity, 
           QtyInHand=p.QtyInHand 
           }; 

      return oppProductss ; 
     } 

我希望這會起作用。