GridView 仅填充 1 个结果

GridView Only populating 1 result

我目前正在努力将数据添加到 GridView。数据来自不同数据库中的 2 个表。目前我能够填充第一个条目,但它不会填充过去。这是代码:

        void FillOrder(int inv)
        {
            var _ord = new OrdersContext();
            var _pro = new ProductContext();

            var qryOrder = (from o in _ord.OrderDetails
                            where o.InvNumberId == inv
                            select new
                            {
                                o.ProductID,
                                o.Quantity
                            }).ToList();
            foreach (var order in qryOrder)
            {
                int prodID = order.ProductID;
                int itemCount = qryOrder.Count;
                var qryProducts = (from p in _pro.Products
                                   where p.ProductID == prodID
                                   select new
                                   {
                                       p.ProductID,
                                       p.ProductName
                                   }).ToList();

                var results = (from t in qryOrder
                               join s in qryProducts
                               on t.ProductID equals prodID
                               select new
                               {
                                   t.ProductID,
                                   t.Quantity,
                                   s.ProductName
                               }).ToList();
                OrderItemList.DataSource = results;
                OrderItemList.DataBind();

            }

        }

任何人都可以帮助解释为什么它只填充第一个条目吗?

如果涉及的产品数量相对较少,(并且由于此查询似乎与一张发票有关,我认为这是真的),那么您可能可以使用类似下面的代码。

这是在移除循环,但是 contains 方法可能会生成一个 SQL 语句,类似于 select ProductID, ProductName from products where productID in (,,,,,,),因此如果参数数量非常大,可能会失败。

var _ord = new OrdersContext();
var _pro = new ProductContext();

var qryOrder = (from o in _ord.OrderDetails
                where o.InvNumberId == inv
                select new
                {
                    o.ProductID,
                    o.Quantity
                }).ToList();

// Get the productIDs 
var productIDS = qryOrder.Select(o=>o.ProductID).Distinct().ToList();

// Get the details of the products used. 
var qryProducts = (from p in _pro.Products
                   where productIDS.Contains(p.ProductID)
                   select new
                   {
                       p.ProductID,
                       p.ProductName
                   }).ToList();

// Combine the two in memory lists
var results = (from t in qryOrder
               join s in qryProducts
               on t.ProductID equals s.ProductID
               select new
               {
                   t.ProductID,
                   t.Quantity,
                   s.ProductName
               }).ToList();

OrderItemList.DataSource = results;
OrderItemList.DataBind();