使用Join with IQueryable LINQ

时间:2015-09-07 07:38:54

标签: c# asp.net-mvc linq join

我正在尝试在两个表opportunityProducts和Products上实现内连接查询,我应该在我的MVC Web API服务中返回Iqueryable元素。但是从下面来看,我无法获得结果,因为它会导致转换错误。

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;
  }

3 个答案:

答案 0 :(得分:1)

您需要填写要返回的Type,而不是返回匿名类型。在这里,因为您正在查询OpportunityProducts,我认为您没有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
                          };

答案 1 :(得分: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;
    }

我希望它可以帮到你。

此致

答案 2 :(得分:0)

我认为你可以创建一个名为ResultProducts的类,它具有所有属性(原始表中的数据类型相同(可以为nullable))你想得到什么。然后你可以返回那个对象。

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 ;
        }

我希望这会奏效。