试图在Linq to Entities中通过子句获得动态顺序。

问题描述 投票:0回答:1

我想通过子句来实现动态顺序,但搞不清楚语法。我以为我已经用inline if语句解决了,但EF不支持这些。

用户将能够选择一个字段来排序(最初是升序),可能是通过点击dgv头。

这是我的代码。-

Dim q = (From customer In db.tblcustomers.Where(Function(x) CBool(x.f_rn >= 0 And x.cu_brn = "00" _
    And (txtFiltAccno.Text.Trim = "" Or x.cu_accno.ToUpper.Contains(txtFiltAccno.Text.ToUpper.Trim)) _
    And (txtFiltCustName.Text.Trim = "" Or       x.cu_name.ToUpper.Contains(txtFiltCustName.Text.ToUpper.Trim)) _
    And (txtFiltPhone.Text.Trim = "" Or x.cu_telno.ToUpper.Contains(txtFiltPhone.Text.ToUpper.Trim)) _
    And (txtFiltFax.Text.Trim = "" Or x.cu_faxno.ToUpper.Contains(txtFiltFax.Text.ToUpper.Trim)) _
    And (txtFiltEmail.Text.Trim = "" Or x.cu_email.ToUpper.Contains(txtFiltEmail.Text.ToUpper.Trim))))
    select customer.f_rn, customer.cu_accno, customer.cu_name, customer.cu_add1, customer.cu_add2,     customer.cu_add3, customer.cu_add4, customer.cu_add5,
            customer.cu_telno, customer.cu_faxno, customer.cu_email).OrderBy(Function(u) 
IIf(a = "cu_name", u.cu_name,
IIf(a = "cu_add1", u.cu_add1,
IIf(a = "cu_add2", u.cu_add2,
IIf(a = "cu_add3", u.cu_add3,
IIf(a = "cu_add4", u.cu_add4,
IIf(a = "cu_add5", u.cu_add5,
IIf(a = "cu_telno", u.cu_telno,
IIf(a = "cu_faxno", u.cu_faxno,
IIf(a = "cu_email", u.cu_email, u.cu_accno)))))))))).Skip((pagenum - 1) * 25).Take(25)
vb.net linq frameworks entity
1个回答
1
投票

Ooof. 这很可能会变成一些讨厌的,而且很可能是性能缓慢的SQL。读一读 https:/use-the-index-luke.comsqlwher-clauseobfuscationsmart-logic。 (不是我想链接到的博客--但我找不到我想的那个博客,那是一个更老派的样子,就像它曾经是一个usenet帖子)

LINQ中的查询是累加的,只有当发生了一些列举结果的事情时,它们才会运行,比如在它上面调用ToArray,或 ForEaching它。这意味着你可以通过几个步骤动态地建立你的查询。(为了清楚起见,我把事情简化了一点,我没有使用实际的列名)。

Dim q as IEnumerable(Of Customer) = db.Customers

If nameTextBox.Text <> "" Then q = q.Where(Function(x) x.Name = nameTextBox.Text)

If ageTextBox.Text <> "" Then q = q.Where(Function(x) x.Age = ageTextBox.Text)

If jobTextBox.Text <> "" Then q = q.Where(Function(x) x.Age = jobTextBox.Text)

If sortByCombo.SelectedValue = "Name" Then q = q.OrderBy(Function(x) x.Name)
Else If ....

如果你只把一些东西放在 Name 盒,该 q 有一个 Where 叫上它。如果你在这3个盒子里都放了什么东西,就会有 Where 是累加的,并且将作为一个与SQL中的术语AND。db查询不会在上述任何一点运行,即使你添加OrderBy。如果你想了解更多关于这方面的信息,请查找 "LINQ延迟执行"。在你尝试读取结果的那一刻,查询将被运行。

ps; 我不确定是否会让DB来做排序,因为每次改变顺序时都需要重新查询--也许只是将结果加载到一个知道如何排序的控件中(大多数网格控件,包括windows和web,都知道如何缓存和排序他们的数据,以避免往返于提供数据的地方),或者使用一个可以处理排序的客户端容器,比如DataTable,SortedList等。

© www.soinside.com 2019 - 2024. All rights reserved.