Linq为所有字段添加条件

时间:2014-04-14 12:07:56

标签: vb.net linq

LINQ和VB.NET

我想将搜索条件放到Table中的所有字段中。 例如:

Dim query = From c in dbContext.MyTable 
      Where c.Field1 = "searchString" or c.Field2 = "searchString" or _
      c.Field3 = "searchString" or …
      Select c

假设我有超过100个字段和更多表。我想写这样的东西:

Dim query = From c in in dbContext.MyTable
     Where Search(c)
     Select c

Private Sub Search(c …??)
    dim cond as string  
    for each field in c
        cond += field.name = "searchstring"
    next
    return cond
End sub

如果这是动态的linq,你可以发给我解决方案(VB.NET)和示例...... 我已经在https://www.nuget.org/packages/System.Linq.Dynamic/查看了System.Linq.Dynamic但是没有示例,也没有建议哪种解决方案最好。有微软的解决方案吗?什么是最好的方法?

感谢。最好的问候。

ADDED

此代码适用于字符串和文本类型。 如何为int和DateTime类型添加解决方案?对于整数,必须是精确数字field = 123,并且当字段为1234或112345时不会显示。

Imports System.Linq.Dynamic

  Dim dbContext As New DevicesLINQDataContext
  Dim columnNames = dbContext.Mapping.MappingSource.GetModel(GetType(DevicesLINQDataContext)).GetMetaType(GetType(VDevices)).DataMembers

  Dim Condition As New StringBuilder
  For Each col In columnNames
      If col.DbType.Contains("char") Then
          Condition.Append(col.Name & ".Contains(@0)").Append(" OR ")
      End If
      If IsNumeric(txtSearch.Text) Then
          If col.DbType.Contains("int") Then
             Condition.Append(col.Name & " = " & CInt(txtSearch.Text)).Append(" OR ")
          End If
      End If
      If col.DbType.Contains("date") Then
          Condition.Append(col.Name & ".Contains(@0)").Append(" OR ") ' Not working????
      End If
  Next
  If Condition.Length > 0 Then
      Condition.Length = Condition.Length - 3 ' removing last OR
      query = System.Linq.Dynamic.DynamicQueryable.Where(query, Condition.ToString, txtSearch.Text)
  End If

已添加2: 对于DateTime或Date类型,我做了下一个解决方案:

If col.DbType.ToLower.Contains("date") then
    If IsDate(txtSearch.Text) And Not txtSearch.Text.Contains(":") Then 
        Condition.Append(col.Name & " > DateTime(" & CDate(txtSearch.Text).AddDays(-1).ToString("yyyy, M, d") & ")").Append(" AND ")
        Condition.Append(col.Name & " < DateTime(" & CDate(txtSearch.Text).AddDays(1).ToString("yyyy, M, d") & ")").Append(" OR ") 
    End If
End if

1 个答案:

答案 0 :(得分:1)

这是linq(请原谅双关语)....我以前熟悉linq.dynamic,但还有其他人......搜索linq.dynamic

http://weblogs.asp.net/scottgu/archive/2008/01/07/dynamic-linq-part-1-using-the-linq-dynamic-query-library.aspx

<强>更新

Dim WhereBuild As New StringBuilder
Dim mySearchString as String = "FindMe"

For Each field In c
    WhereBuild.Append(field.Name).Append(" = """).Append(mySearchString).Append(""" OR ")
Next
'Remove last  'OR'
WhereBuild.Remove(WhereBuild.Length-3, 3)


'Build query
Dim dc as New myDataContext

Dim AList = dc.MyTable _
            .Where(WhereBuild.ToString) _
            .OrderBy(ddl_SortBy.SelectedValue)

'Here I bind my results to a gridview
myGridView.DataSource = AList
myGridView.DataBind()

.OrderBy(ddl_SortBy.SelectedValue)是可选的。 ddl_SortBy将包含字段名称作为值。 *从头开始输入未经测试。