vb.net - Linq add condition to all fields -
linq , vb.net
i put search condition fields in table. example:
dim query = c in dbcontext.mytable c.field1 = "searchstring" or c.field2 = "searchstring" or _ c.field3 = "searchstring" or … select c
assume have more 100 fields , more tables. write this:
dim query = c in in dbcontext.mytable search(c) select c private sub search(c …??) dim cond string each field in c cond += field.name = "searchstring" next return cond end sub
if dynamic linq post me solution (vb.net) , example , … in https://www.nuget.org/packages/system.linq.dynamic/ system.linq.dynamic there no example , no suggestion solution best. have microsoft solution this? best approach?
thanks. best regards.
added
this code works string , text type. how add solution int , datetime type?? integer must exact number field = 123 , not show when field 1234 or 112345.
imports system.linq.dynamic dim dbcontext new deviceslinqdatacontext dim columnnames = dbcontext.mapping.mappingsource.getmodel(gettype(deviceslinqdatacontext)).getmetatype(gettype(vdevices)).datamembers dim condition new stringbuilder each col in columnnames if col.dbtype.contains("char") condition.append(col.name & ".contains(@0)").append(" or ") end if if isnumeric(txtsearch.text) if col.dbtype.contains("int") condition.append(col.name & " = " & cint(txtsearch.text)).append(" or ") end if end if if col.dbtype.contains("date") condition.append(col.name & ".contains(@0)").append(" or ") ' not working???? end if next if condition.length > 0 condition.length = condition.length - 3 ' removing last or query = system.linq.dynamic.dynamicqueryable.where(query, condition.tostring, txtsearch.text) end if
added 2: type datetime or date made next solution:
if col.dbtype.tolower.contains("date") if isdate(txtsearch.text) , not txtsearch.text.contains(":") condition.append(col.name & " > datetime(" & cdate(txtsearch.text).adddays(-1).tostring("yyyy, m, d") & ")").append(" , ") condition.append(col.name & " < datetime(" & cdate(txtsearch.text).adddays(1).tostring("yyyy, m, d") & ")").append(" or ") end if end if
this linq (pardon pun).... used familiar linq.dynamic there others.... search linq.dynamic
update
dim wherebuild new stringbuilder dim mysearchstring string = "findme" 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 new mydatacontext dim alist = dc.mytable _ .where(wherebuild.tostring) _ .orderby(ddl_sortby.selectedvalue) 'here bind results gridview mygridview.datasource = alist mygridview.databind()
.orderby(ddl_sortby.selectedvalue) optional. ddl_sortby contain field names values. *type scratch not tested.
Comments
Post a Comment