Linq to SQL C#获取所有子/子子类别中的产品太慢

vts*_*vts 5 c# linq asp.net linq-to-sql

在所选主要类别的所有子类别中获取所有产品的最佳方法是什么?试图在大约80个子类别中获得10000个产品,但这种方法太慢了.有什么建议?使用c#和Linq来SQL

//list for the child categories
private List<int> catsChildList = new List<int>();

GetChildCats(123);

//get all the child categories of main category '123'

private void GetChildCats(int _parentCat)
{
    var cats = (from c in db2.tbl_cart_categories
                where c.ParentID == _parentCat
                select new { c.CategoryID });
    if (cats.Count() > 0)
    {
        foreach (var cat in cats)
        {
            int _cat = Convert.ToInt32(cat.CategoryID);
            catsChildList.Add(_cat);
            GetChildCats(_cat);
        }
    }
}

//Get the products
var products = (from p in db2.products_infos
            where  p.IsEnabled == true
            group p by p.ProdID
            into g where g.Any(x => catsChildList.Contains(Convert.ToInt32(x.CategoryID)))
Run Code Online (Sandbox Code Playgroud)

返回结果大约需要6秒钟

sgm*_*ore 3

有什么区别

var products = 
    (
     from p in db2.products_infos
     where  p.IsEnabled == true
     group p by p.ProdID
     into g where g.Any(x => catsChildList.Contains(Convert.ToInt32(x.CategoryID)))
     select g
    );
Run Code Online (Sandbox Code Playgroud)

 var tmpList = 
    (
     from p in db2.products_infos
     where  p.IsEnabled == true 
            && catsChildList.Contains(Convert.ToInt32(p.CategoryID))) 
     select p
    ).ToList();

 var products = 
     (from r in tmpList group p by r.ProdID into g select g);
Run Code Online (Sandbox Code Playgroud)

也许我的架构不同,但是当我使用 Linq2Sql 尝试此操作时,它似乎返回相同的结果,但后者在一个数据库命中中返回所有结果,而前者发出多个请求。(如果返回的产品数量为 10000,则将执行 10001 次数据库请求)。