繁体   English   中英

结合使用IQueryable LINQ

[英]Using Join with IQueryable LINQ

我正在尝试在两个表aboveProducts和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;
  }

您需要填写要返回的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
                          };

我在您的代码中看到错误。 您应该返回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;
    }

希望对您有帮助。

问候,

朱利奥

我认为您可以创建具有所有属性的ResultProducts类(具有与原始表中相同的数据类型(也可以放入null)的所有属性)您想要获得的属性。 然后,您可以返回该对象。

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

我希望这会起作用。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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