用linq编译查询

时间:2012-09-07 13:23:28

标签: .net sql vb.net linq

您好我刚刚发现我的网络应用程序很慢,可能是因为linq。

我对这些编译的查询感到很遗憾,你能帮我编译一个查询并仍然可以查询查询吗? (这是可以理解的吗?:p) 例如这个查询(在vb.net中):

 Dim query = (From p In db.ProductCategories _
               Group Join t In db.Translate_ProductCategories On p.ID_Category Equals t.Category_ID Into res = Group From r1 In res.DefaultIfEmpty _
               Where r1.Language_ID = langID And p.CategoryActive = True _
               Select New With {.name = r1.Name, .idcat = p.ID_Category, .level = p.CategoryLevel, .index = p.CategoryIndex, .parentID = p.CategoryParent_ID})

然后我想确保仍然可以做这些事情:

Dim level0 = (From l In query Where l.level = 0 Order By l.index Ascending Select l)

感谢您的帮助

编辑:

我试过这样做:

Dim myquery = CompiledQuery.Compile( _
    Function(db As EshopDataContext) _
      (From p In db.ProductCategories _
               Group Join t In db.Translate_ProductCategories On p.ID_Category Equals t.Category_ID Into res = Group From r1 In res.DefaultIfEmpty _
               Where r1.Language_ID = langID And p.CategoryActive = True _
               Select New With {.name = r1.Name, .idcat = p.ID_Category, .level = p.CategoryLevel, .index = p.CategoryIndex, .parentID = p.CategoryParent_ID}))

Dim query = myquery.Invoke(db)

Dim level0 = (From l In query Where l.level = 0 Order By l.index Ascending Select l)

我有错误“查询结果不能多​​次枚举。”在这一行

cptCat1 = level1.Where(Function(l1) l1.parentID = parentId1).Count

1 个答案:

答案 0 :(得分:1)

首先阅读: http://www.codinghorror.com/blog/2010/03/compiled-or-bust.html

如果你真的认为你必须阅读它,那么这是MS编译查询的方法。

http://msdn.microsoft.com/en-us/library/bb399335.aspx#Y0(对于linq2sql)

http://msdn.microsoft.com/en-us/library/bb896297.aspx#Y300(对于linq2EF)